【问题标题】:how to execute function that dependent on 2 observables如何执行依赖于 2 个 observables 的函数
【发布时间】:2019-12-08 23:59:39
【问题描述】:

我有一个函数需要从 2 个单独的异步函数(返回 observables)中获取 2 个响应。 1.func1返回可观察对象 2.func2返回observable 它们不相互依赖——它们可以单独运行。 Func 3 应该有一些 Func1 和 Func2 的结果如何执行。 我正在使用 RXJS,并尝试使用管道和 flatMap 或地图进行操作,但仍然 - 没有管理。

【问题讨论】:

标签: angular rxjs observable


【解决方案1】:

为此,您需要forkJoin。在这里试一试:

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)
    )
  }

}

这里有一个Working Sample StackBlitz 供您参考。

【讨论】:

    猜你喜欢
    • 2021-04-02
    • 1970-01-01
    • 2019-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-06
    • 2023-03-31
    • 2019-02-03
    相关资源
    最近更新 更多