2017-06-26 25 views
0

オブジェクトに2つのidがある場合、最初のオブジェクトが取得された後に2つの呼び出しを行う観測可能なストリームがあります。 idの1つはオプションであり、そこに存在していなくてもよい。 siteIdはオプションのIDです。見つかった場合は、getTeamと同じように呼び出しを行う必要があります。条件付きコールを作成するにはどうすればよいですか?私がこれを動作させることができた唯一の方法は、subscribeメソッドのidをチェックし、そこから呼び出しを行うことでした。しかし、コードには避けたいネストされたサブスクリプションがあります。条件付き呼び出しで観察可能なストリーム

private getZone() { 
    this.spinner.show(); 

    this.zonesService.getZone(this.zoneId) 
     .map(response => { 
     this.zone = response['group']; 
     this.teamId = this.zone['TeamId']; 
     this.siteId = this.zone['SiteId']; 
     return this.zone; 
     }) 
     .flatMap(() => this.teamsService.getTeam(this.teamId)) 
     .map(response => { 
     if (response['team']) { 
      this.team = response['team']; 
      if (this.team['personal']) { this.team['name'] = 'Personal Team'; } 
      this.zone['teamName'] = this.team['name']; 
     } 
     return response; 
     }) 
     .subscribe(
     _data => { 
      if (this.zone['personal']) { this.zone['name'] = 'My Personal Zone'; } 
      if (this.siteId) { 
      this.sitesService.getSite(this.siteId) 
       .subscribe(
       _data => { 
        this.site = _data['site']; 
       } 
      ); 
      } 

      this.spinner.hide(); 
      this.loading = false; 
     } 
    ); 
    } 

ご協力いただければ幸いです。ありがとう。

答えて

0

あなたはあなたの最初のflatMap()

this.zonesService.getZone(this.zoneId) 
    .flatMap(response => { 
     this.zone = response['group'] 

     if(this.zone.SiteId){ 
      // make these 2 api calls in parallel 
      return Observable.forkJoin(
       this.getTeam(this.zone.TeamId), 
       this.getSite(this.zone.SiteId) 
      ); 
     }else{ 
      // make single api call 
      return this.getTeam(this.zone.TeamId); 
     } 
    }).subscribe(response => { 
     // note that your response will be different based on the flatMap(). 
     // When you do the 2 calls in parallel, your response = [getTeamResponse, getSiteResponse] 
     // but when you just do the single call, your response = getTeamResponse 
     // so you'll need a check in here to account for that 
    }); 

だから機能的に何が起こっているか、あなたの最初のAPI呼び出しを行うことで内部のforkJoin()メソッドを使用することができます。そのレスポンスがサイトIDを返す場合は、&のサイトコールを並行して実行します。それ以外の場合は、1つのチームコールを行います。ここで

はforkJoinに良いリソースです:https://coryrylan.com/blog/angular-multiple-http-requests-with-rxjs

+0

ありがとう、それはうまくいきました。 – Aaron

0

私が間違っていない場合は、ストリームを分割して(多分共有して)、別の呼び出しを行う場合は、最初の呼び出し(zonesService.getZone)で使用する必要があるすべての値を取得します2つのエンドポイントを使用すると、両方を並行して処理でき、sitesService.getSite(defaultIfEmpty演算子)に「null」オブザーバブルを使用し、最後にzip関数でemを再度マージすることができます。

+0

ありがとうございました。私はRXJSを学んでいます。私の仕事は、フロントとバックエンドの両方を行う現時点で余分な責任に関わっているので、私は本当にドキュメントに入る時間がありませんでした。あなたのソリューションは恐らく素晴らしいでしょう。私は試してみましたが、コードにまとめるための十分な知識はありませんでした。私は本当にあなたの提案から学ぶことが好きだったでしょう。あなたがクールなコード例を追加する時間があれば。 – Aaron

関連する問題