簡體   English   中英

RxJ:一個接一個地執行3個可觀察對象,並使用第一個請求,第二個請求和第三個請求的結果

[英]RxJs: Executing 3 observables one after another and using results from first in second, and first and second in third requests

我需要能夠一個接一個地執行3個可觀察變量,以便可以在第二個中使用第一個結果,在第三個中使用第一個和第二個結果。

這樣的事情( 由於serviceId在第三個請求中不可見,因此不起作用 ):

private setupStuff(): void {
        this.initRouteParams().pipe(
            switchMap(serviceId => this.getFileInfo(serviceId)),
            switchMap(fileName => this.getExistingFile(serviceId, fileName)
                .subscribe(response => {
                    console.log(response);
                }))
            );
    }

您可以將serviceN的值顯式返回給serviceN + 1。 這是個主意:

private setupStuff() {
  this.initRouteParams()
    .pipe(
      switchMap(serviceId => {
        return zip(of(serviceId), this.getFileInfo(serviceId))
      }),
      switchMap(([serviceId, filename]) => {
        return zip(of(serviceId), of(filename), this.getExistingFile(serviceId, filename))
      })
    )
    .subscribe(([serviceId, filename, response]) => {
      console.log(serviceId, filename, response);
    })
}

編輯:

您可以通過顯式聲明每個輸入的類型來修復類型錯誤。 您可能想為response分配適當的類型。

設法這樣解決:

private checkFilePresence(): void {
        const first$: Observable<string> = this.initRouteParams();
        const second$: Observable<string> = first$.pipe(
            switchMap(config => {
                return this.getFileInfo(config);
            })
        );
        const third$: Observable<CkitExistingFileResponse> = combineLatest(first$, second$).pipe(
            switchMap(([config, second]) => {
                return this.getExistingFile(config, second);
            })
        );
        combineLatest(first$, third$)
            .subscribe(() => {
            });
    }

您可以按以下順序訂閱可觀察對象:

private setupStuff(): void {
        this.initRouteParams().subscribe( serviceId => {
            this.getFileInfo(serviceId).subscribe(fileName => {
               this.getExistingFile(serviceId, fileName).subscribe( response => {
                   console.log(response);
                });
            });
        });
}

暫無
暫無

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

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