2017-05-18 12 views
0

現在、私はREST呼び出しで従業員情報を取得する小さなAngularアプリを実行しています。しかし、api/department/:departmentId/employee/:employeeIdのようなリクエストを処理している間に固まった。ここに事があります:ngOnInit()に、私はDepartmentServiceを最初に呼び出して、その結果をEmployeeService上のものに照会する必要があることを知っています。例えば、私はこれを試してみたRxJS +角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

あなたは、少なくとも1 subscribe削除することができます:それはroute.snapshot.paramsを使用して、よりを簡略化することができ

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

は:

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

関連する問題