2017-05-18 74 views
0

我正在做一個小的Angular應用程序,它將通過REST調用檢索一些員工信息。但是,在處理類似api/department/:departmentId/employee/:employeeId的請求時,我被卡住了。這是事情:在ngOnInit(),我知道我需要首先調用DepartmentService,然後使用它的結果來查詢EmployeeService上的東西。基於角度教程中,我通常會這麼做只有一個參數:使用RxJS + Angular 4調用多個同步服務

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,但是我還沒有成功實現。請記住,我需要這兩個服務的結果,以便子組件可以使用它們進行渲染,並且最好處理來自兩個調用的錯誤(最終它們將是網絡調用)。

回答

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; 
     }); 
    }); 
+0

無法實現的簡化版本,getDepartmentById返回一個承諾。第一個版本結果很好! –

+1

還有一個選項可以使用Observable.fromPromise(getDepartmentById(...)) – karser