如何执行依赖于2个可观察对象的函数

时间:2019-07-31 12:53:11

标签: angular rxjs observable

我有一个需要从2个单独的异步函数(返回可观察值)获得2个响应的函数。 1. Func1返回可观察 2. Func2返回可观察 它们彼此不依赖-它们可以单独运行。 Func 3应该具有如何执行Func1和Func2的结果。 我正在使用RXJS,并尝试使用pipe和flatMap或map进行操作,但仍然-没有管理。

1 个答案:

答案 0 :(得分:4)

您需要exceptions。这里试试看:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { forkJoin } from 'rxjs';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  constructor(private http: HttpClient) {}

  getGoogle() {
    return this.http.get('https://api.github.com/users/google');
  }

  getMicrosoft() {
    return this.http.get('https://api.github.com/users/microsoft');
  }

  ngOnInit() {
    forkJoin(
      this.getGoogle(),
      this.getMicrosoft()
    )
    .subscribe(
      res => console.log(res)
    )
  }

}

  

这是您推荐的forkJoin