2017-06-26 19 views
0

可觀察到流我有一個觀察的數據流,使兩個呼叫最初的對象是使用檢索經過兩次的ID在對象中找到。其中一個ID是可選的,可能會或可能不會。 siteId是可選的ID。如果發現我必須完全按照getTeam的要求撥打電話。我如何進行條件性調用?我能夠得到這個工作的唯一方法是通過檢查訂閱方法中的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

可以使用forkJoin()方法,你的第一個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一個很好的資源:https://coryrylan.com/blog/angular-multiple-http-requests-with-rxjs

+0

謝謝,那很好。 – Aaron

0

,如果我沒有錯,你有你需要的,如果你在這一點上(也許共享)劃分流上首次呼叫(zonesService.getZone)使用,並進行單獨的調用的其他所有值2個終點,你可以並行同時處理,並使用「空」可觀察的sitesService.getSite(defaultIfEmpty運營商),然後最後用拉鍊功能再次合併他們。

+0

謝謝。我只是在學習RXJS。由於我的工作是如此涉及額外的責任在這個時候做前端和後端我還沒有時間去真正進入文檔。你的解決方案可能很棒。雖然我確實嘗試過,但我沒有足夠的背景知識將它們放在代碼中。我真的很喜歡從你的建議中學習。如果您有時間添加一個很酷的代碼示例。 – Aaron