我目前正在做一个小型的Angular应用程序,它将通过REST调用检索一些员工信息。但是,在处理类似于api/department/:departmentId/employee/:employeeId
的请求时,我遇到了困难。事情就是这样:在ngOnInit()
上,我知道我需要首先调用DepartmentService,然后使用其结果来查询EmployeeService上的内容。基于Angular教程,我通常会使用一个参数:
this.router.params.switchMap((params: Params) =>
this.employeeService.getEmployee(+params['employeeId'])).subscribe(employee => {
this.employee = employee;
}
);
我试过这个,例如:
this.router.params.switchMap((params: Params) =>
this.departmentService.getDepartmentById(+params['id'])).subscribe(department => {
this.department = department;
this.router.params.switchMap((params: Params) =>
this.employeeService.getEmployee(+params['employeeId'])).subscribe(employee => {
this.currentEmployee = employee;
this.equipment = this.currentEmployee.equipments.find(eq => {
return eq.employeeId === this.currentEmployee.id && eq.departmentId === this.department.id;
});
}
);
}
);
我不确定使用Params链接呼叫的首选方法是什么。我读过Defer和BindCallback,但我还没有成功实现。请记住,我需要来自两个服务的结果,以便子组件可以使用它们进行渲染,并且最好处理来自两个调用的错误(最终它们将是网络调用)。
答案 0 :(得分:1)
您可以删除至少一个subscribe
:
this.route.params
.do((params: Params) => this.params = params)
.switchMap(() => this.departmentService.getDepartmentById(+this.params['id']))
.do((department) => this.department = department)
.switchMap(department => this.employeeService.getEmployee(+this.params['employeeId']))
.subscribe(employee => {
this.currentEmployee = employee;
this.equipment = this.currentEmployee.equipments.find(eq => {
return eq.employeeId === this.currentEmployee.id && eq.departmentId === this.department.id;
});
});
使用route.snapshot.params
:
this.departmentService
.getDepartmentById(+this.route.snapshot.params['id'])
.do((department) => this.department = department)
.switchMap(department => this.employeeService.getEmployee(+this.route.snapshot.params['employeeId']))
.subscribe(employee => {
this.currentEmployee = employee;
this.equipment = this.currentEmployee.equipments.find(eq => {
return eq.employeeId === this.currentEmployee.id && eq.departmentId === this.department.id;
});
});