I've reading up on interfaces and type assertion. Been looking at pages like:
I'm getting the hang of it, and it's pretty straightforward in understanding the basics. Though: Nowhere do I find how to type a JSON object to a object I use in my app, when HTTP is involved.
For example, I have an Array of Teacher-objects. Each Teacher has an id, name and an Array of Students. I have another class Students that contain their attributes..... etc.
Somewhere in those links I read that, unless you need to perform actions to an object, it's enough to have just an Interface. But unless you want to do actions to the Object you need a separate class?
My actual Teacher class begins with... :
export class Teacher {
private students: Array<Student>;
constructor(public id: string, public name: string) {
this.students = new Array<Student>();
}
public getStudents(): Array<Student> {
retu this.students;
}
public addStudent(value: Student) {
this.students.push(value);
}
---some other methods---
}
So as you see, the students array is private in the class and I do have other methods: adding, removing and getting a Teacher by id.
First of all, how would the code look like if I want to cast (or assert the type) the JS object to a Teacher object?
Now my code looks something like this:
Service:
getTeachers() {
retu this.http.get('someUrl')
.map((res: Response) => res.json())
}
saveStudent(student: Student) {
...
retu this.http.post('someUrl')
.map((res: Response) => res.json())
}
Component (Angular 2 Component):
export class ListComponent implements OnActivate {
id: string;
name: string;
teachers: Teacher[];
constructor(public _service: Service, public _router: Router) {
}
routerOnActivate(): void {
this._service.getTeachers()
.subscribe(teachers => this.teachers = teachers);
}
saveStudent() {
let student = new Student(this.id, this.name)
this._service.saveStudent(student)
.subscribe(student => this.students.push(student));
this._service.getStudents()
.subscribe(students => this.students = students);
}
My interface would look like:
export interface TeacherJSON {
id: string,
name: string,
students: Array<Student>;
}
So obviously I need to first change my teachers array in the component to an instance of my interface? How? Just like: teachers: TeacherJSON[] ??
If the the above interface is not enough to be able to perform actions on the object, how do I move forward? I did lea that you can add methods to your interface like:
interface Thing {
a: number;
b: string;
foo(s: string, n: number): string;
}
process(x: Thing) {
retu x.foo("abc");
}
I do understand the above example, but I guess the http, mapping and subscribing is throwing me off, and I don't know how to implement it in my code!
