簡體   English   中英

Angular 多個可觀察的 http 調用一次后調用

[英]Angular multiple observable http calls after one complated

我有多個服務從服務器獲取 http 響應。

export abstract class ServiceBase<T>{
    getAll(){console.log(`${this.url}/${this.endpoint}`)
        return this.http.get<any[]>(`${this.url}/${this.endpoint}`);
    }

    get(id: any){
        return this.http.get<any>(`${this.url}/${this.endpoint}/${id}`);
    }
}

@Injectable()
export class Service1 extends ServiceBase<any> {
    constructor(http: HttpClient) {
        super(http, "http://localhost:60211", "s1");
    }
}

@Injectable()
export class Service2 extends ServiceBase<any> {
    constructor(http: HttpClient) {
        super(http, "http://localhost:60211", "s2");
    }
}


@Injectable()
export class Service3 extends ServiceBase<any> {
    constructor(http: HttpClient) {
        super(http, "http://localhost:60211", "s3");
    }
}

我在應用程序中使用它。

export class AppComponent {
     s1: {};
     s2: any[];
     s2: any[];
     constructor(service1:Service1, service2:service2, service3:service3){
        service1.get("123").subscribe({       
          next: response => {
            this.s1=response;
            service2.getAll().subscribe({
                    next: response => {
                        this.s2 = response;
                    }
            });
            service3.getAll().subscribe({
                    next: response => {
                        this.s3 = response;
                    }
            })
          }
         })
     }
}

但是 s3 和 s2 響應不是來自服務器。 這是不是這種用法是錯誤的? 但是當我從 postman 運行服務時,服務正在運行。

你需要 pipable 操作符switchMapcombineLatest來實現你想要的。

它看起來像這樣:

service1.get("123").pipe(
    switchMap(() => combineLatest(service2.getAll(), service3.getAll())),
).subscribe(([service2Data, servoce3Data]) => {
    // do your stuff
});

這是一個forkJoin的示例。 為確保語法正確且有效,這是來自我的代碼(而不是來自 OPs 代碼)。

  // Suppliers for the selected product
  // Only gets the suppliers it needs
  // switchMap here instead of mergeMap so quickly clicking on the items 
  // cancels prior requests.
  selectedProductSuppliers$ = this.selectedProduct$
    .pipe(
      filter(selectedProduct => Boolean(selectedProduct)),
      switchMap(selectedProduct =>
        forkJoin(selectedProduct.supplierIds.map(supplierId => this.http.get<Supplier>(`${this.suppliersUrl}/${supplierId}`)))
      ),
      tap(suppliers => console.log('product suppliers', JSON.stringify(suppliers)))
    );

此代碼在選擇新產品時收到通知( this.selectedProduct

然后,它通過一組操作管道選擇:

  • 它過濾掉一個 null selectedProduct (例如當頁面首次顯示並且用戶尚未選擇產品時)

  • 它使用 switchMap,所以如果用戶選擇產品 1,沒有產品 2,沒有產品 3,快速連續,它只會發出產品 3。

  • 它使用 forkJoin 獲取為所選產品定義的每個供應商 ID,並使用它來獲取供應商詳細信息數據,然后將所有供應商合並到一個數組中並發出該數組。

selectedProductSuppliers然后是Observable<Supplier[]>並發出所選產品的供應商數組。

你可以在這里找到完整的代碼集: https://github.com/DeborahK/Angular-RxJS

暫無
暫無

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

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