我想调用两个可观察对象,第二个在 Angular2 中的第一个之后调用

I want to call two observables with the second called after the first one in Angular2

我想调用两个可观察对象,第二个在第一个之后调用。

我有一个 observable 也被先订阅了。 然后我希望第二个可观察对象嵌套在第一个可观察对象中。

我想在下面合并这两个订阅:

this.serviceA.getData()
.takeUntil(destroyed$)
.subscribe(item => {

});

this.serviceB.getData()
.takeUntil(destroyed$)
.subscribe(item => {

});

这是我展示我想做的事情的尝试(更新)

  destroyed$: Subject<any> = new Subject<any>();

  ngOnInit(): void {
    this.serviceA.getData
      .takeUntil(this.destroyed$)
      .concatMap(dataA => {
        this.myDataA= dataA;    

        return this.serviceB.getData;
      })
      .takeUntil(this.destroyed$)
      .subscribe(dataB => {            

         this.myDataA.forEach(item => {
             item.visible = dataB.find(o => o.id === item.label).isVisible;
         }); 

      });
  };

  ngOnDestroy(): void {
    this.destroyed$.next(true);
    this.destroyed$.complete();
  };

目的是在第一个订阅之后调用第二个嵌套订阅,因为在第二个订阅中需要来自第一个订阅者的数据

好问题 (Y),

您需要使用forkJoin docs

Runs all observable sequences in (parallel) and collect their last elements.

示例:

let character = this.http.get('https://swapi.co/api/people/1').map(res => res.json());
let characterHomeworld = this.http.get('http://swapi.co/api/planets/1').map(res => res.json());

Observable.forkJoin([character, characterHomeworld]).subscribe(results => {
  // results[0] is our character
  // results[1] is our character homeworld
  results[0].homeworld = results[1];
  this.loadedCharacter = results[0];
});

参考:https://coryrylan.com/blog/angular-multiple-http-requests-with-rxjs

因此,对于您的具体情况,您可以执行以下操作:

let obs1 = this.serviceA.getData()
let obs2 = this.serviceB.getData()

Observable.forkJoin([obs1, obs2]).subscribe(results => {
  // results[0] is our obs1
  // results[1] is our obs2
  // show the bigger array
  this.items = results[0] > results[1] ? results[0] : results[1]
});

但是如果你需要一些依赖于另一个的数据,你可以这样做

showData() {
  let firstData;
  this.serviceA.getData()
    .map((firstNeededData) => {
      firstData = firstNeededData
      return this.serviceB.getData()
    })
    .subscribe(secondNeededData => {
      // I need to show the bigger 
      this.theBigger = secondNeededData > firstData ? secondNeededData : firstData
    })

}

接受的答案不正确。 forkJoin 将同时订阅两个 Observables,而你想先订阅第一个,然后在订阅完成后订阅第二个。

这通常使用 concatMap 运算符完成:

this.serviceA.getData()
  .concatMap(response => this.serviceB.getData())
  .subscribe(...)

如果您想合并两个响应,可以在 serviceB.getData() 之后使用 map

this.serviceA.getData()
  .concatMap(responseA => this.serviceB.getData()
    .map(responseB => /* combine responseA and responseB */ ))
  .subscribe(...)