簡體   English   中英

Angular 6+,如何調用多個內部可觀察服務並等待從內部到外部訂單的結果表

[英]Angular 6+ , How Call Multi Inner Observable Services And Wait For Getting Result Form Inside To Outside Order

我有一個組件-A.ts 文件,它有一個方法-A(),它從服務-B() 調用方法-B()(我試圖使它成為可觀察的方法,所以我不確定我做了它正確),像這樣

FacilityDetailGridComponent.ts

updateNursingUnitList(getUpdate: boolean) {

    const recipeObs = this.nursingUnitEditableTableService.updateNursingUnitList(getUpdate, this.projectID, this.facilityID);

    recipeObs.subscribe(
      data => {
        this.nursingUnitList = data;
      }
    );
  }

我需要在這一點上停止以獲得完整/完整的響應然后繼續,

在 service-B() 的 method-B() 中,我從 Service-C() 中調用 method-C() 也是 Observable(並且我確定它可以正常工作),就像這樣

NursingUnitEditableTableService.ts

updateNursingUnitList(getUpdate: boolean, projectID: number, facilityID: number): Observable<any[]> {

    if (getUpdate == true) {

      this.nursingUnitService.getAllUnits(projectID, facilityID).subscribe(
        (data: nursingUnit[]) => {
          return of(data);
        },
        error => {
          if (error.status == 400) {
            this.errorMsg = "Bad Request Error";
            return of(null);
          }
          if (error.status == 404) {
            this.errorMsg = error.error;
           return of(null);
          }
        }
      )
    } else {
      return of(null);
    }    
  }

Service-C() 和 method-c() 是這樣的,

NursingUnitService.ts

  getAllUnits(projectID: number, facilityID: number): Observable<nursingUnit[]> {
    return this.http.get<nursingUnit[]>(this.baseUrl + `api/FacilityProperties/GetAllUnits/${projectID}/${facilityID}`);
  }

所以,如你所見,我需要修改中間服務(Service-B 和 Method-B())以某種方式等待內部服務和方法(Service-C 和 method-C() 它已經是可觀察的)然后獲得完整的響應,將(finalResopne)返回到調用它的組件(組件-A,方法-A())

非常感謝您的幫助!

您可以在rxjs 中使用mergeMap運算符來鏈接服務調用。

例子:

import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { mergeMap } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: 'app/app.component.html'
})
export class AppComponent {
  homeworld: Observable<{}>;
  constructor(private http: HttpClient) { }

  ngOnInit() {
    this.homeworld = this.http.get('/api/people/1').pipe(
      mergeMap(character => this.http.get(character.homeworld))
    );
  }
}

此示例使用mergeMap也稱為flatMap來映射/迭代 Observable 值

因此,在我們的示例中,當我們獲得 homeworld 時,我們將在我們的角色 Observable 流中返回一個 Observable。 這會在 Observable 中創建一個嵌套的 Observable。

mergeMap 運算符通過訂閱並將值從內部 Observable 中提取出來並將其傳遞回父流來幫助我們。 這大大壓縮了我們的代碼並消除了對嵌套訂閱的需要。

它看起來像這樣( 來源]:

mergeMap observables 示意圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM