簡體   English   中英

RXJS-如何使用2個不同的可觀察結果作為函數調用的參數

[英]RXJS - How to use the result of 2 different observable as parameters for a function call

我有2個可觀察值(異步)。 第一個返回狀態數組,其中每個狀態都有一個等級。 第二個返回一個用戶數組,其中包含每個用戶的狀態。

我正在嘗試輸出按狀態排序的用戶列表。

這是我嘗試過的:

const sortedUserList$: Subject<any> = new Subject();
this.getStatusList()
  .pipe(take(1))
  .subscribe(statusList=> {
    this.getUserList()
      .pipe(take(1))
      .subscribe(userList=> {
        // ... sorting algo using both statusList and userList
        sortedUserList$.next(centersPlanning);
      });
  });

顯然,它不起作用,因為statusList在第二個subscribe不可用,因為它不在其范圍內。

它也不像嵌套2個subscribte這樣做是利用rxJS事情的正確方法。

我也嘗試過使用mergeMap但沒有更多成功。

謝謝並恭祝安康

您可以使用forkJoin的forkJoin。 嘗試這樣的事情:

import { forkJoin, of, Subject } from 'rxjs'
import {take, delay} from 'rxjs/operators'



sortedUserList: Subject<any> = new Subject();

//For demonstration purposes
getStatusList() {
    return of('first').pipe(
        delay(2000)
    );
}

//For demonstration purposes
getUserList() {
    return of('second').pipe(
        delay(1000)
    )
}

ngOnInit() {
    forkJoin(
        this.getStatusList(),
        this.getUserList()
    ).pipe(
        take(1)
    ).subscribe(resp => {
        console.log(resp) // ['first', 'second']
        //Do whatever you want with both responses here.
        this.sortedUserList$.next(centersPlanning)
    })
}

檢查一下stackblitz

暫無
暫無

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

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