我正在学习HTTP。不确定如何前进。我只在我的服务中进行http呼叫。
然后我有一个班级,老师,这里有一些方法:
export class Teacher {
public addStudent(value: Student): void {
this.students.push(value);
}
}
我有一个列出教师的列表组件,在该组件中,用户可以单击教师并移动到详细页面,在该页面上,用户输入并将学生添加到教师。
export class TeacherDetailComponent implements OnActivate {
teacher: Teacher;
constructor(public _service: Service, public _router: Router) { }
routerOnActivate(curr: RouteSegment): void {
let id = curr.getParam('id');
this._service.getById(id)
.subscribe(teacher => {
this.teacher = teacher;
});
}
addStudent() {
this.teacher.getStudents().push(new Student());
//what code here?
}
}
有我的headscratcher,我如何以及在何处告诉Angular在添加新学生时更新教师的数据!
答案 0 :(得分:2)
实际上,您的问题与组件通信有关。我会为此创建一个共享服务。
有关详细信息,请参阅此文档:
因此,我将创建一个服务来通知列表组件添加或删除学生,以便相应地更新列表。这是一个示例:
@Injectable()
export class StudentService {
userAdded:Subject<Student> = new Subject();
userDeleted:Subject<Student> = new Subject();
constructor(private http:Http) {
}
addStudent(student:Student) {
return this.http.post('/users', ...)
(...)
.do((addedStudent) => {
this.userAdded.next(addedStudent);
});
}
deleteStudent(student:Student) {
return this.http.post('/users', ...)
(...)
.do((removedStudent) => {
this.userRemoved.next(removedStudent);
});
}
}
因此,您可以更新详细信息组件:
addStudent() {
let newStudent = new Student();
this.studentService.addStudent(newStudent).subscribe(addedStudent => {
this.teacher.getStudents().push(addedStudent);
});
}
在列表组件中:
this.studentService.addedStudent.subscribe(addedStudent => {
// do something
});