【问题标题】:What is the proper method for using the output of one observable as the input to another in angular使用一个可观察对象的输出作为另一个可观察对象的输入的正确方法是什么?
【发布时间】:2019-10-08 21:01:43
【问题描述】:

我需要调用具有异步 (http) 返回的服务,并将其输出用作服务方法(返回可观察对象)的附加输入。在 Angular 4+ 中执行此操作的最佳方法是什么?

我已经尝试在第一个服务的“订阅”方法中“链接”结果,但这样做我的服务总是返回“null”。

public secondServiceCall: Observable<object> {
   this.firstService.next().subscribe(result=> {
      item.number = result;

      return this.httpService.post<object>('/new', item);
   });
}

我预计在 firstService 的订阅完成之前该函数不会返回(类似异步),但这并没有发生 - 相反,我在调用函数中得到了“null”。

我还尝试将 firstService 调用用作可观察对象 - 这会正确返回第二个可观察对象,但在触发第二个可观察对象之前从不等待“then”函数执行。

this.firstService.next().toPromise().then(result=> {
  item.number = result;
});

return return this.httpService.post<object>('/new', item);

【问题讨论】:

  • 我知道 switchMap 运算符,但我找不到任何有用的示例来说明如何等待第一个结果,然后触发第二个 observable。你能扩展你的链接吗?
  • 这个链接有很多例子。 return call1().pipe(switchMap(response1 =&gt; call2(response1))

标签: angular asynchronous rxjs observable


【解决方案1】:

导入switchMap操作符:

import { switchMap } from 'rxjs/operators';

无论firstService 中的任何方法返回item 的可观察对象,都将其包装成这样:

public secondServiceCall: Observable<object> {
   return this.firstService.someMethod().pipe(
      switchMap(item => {
         return this.httpService.post<object>('/new', item);
      })
   ) // result of your HTTP call based on item from firstService is now available when you subscribe
}

它的作用是执行返回Observable&lt;item&gt;firstService 方法,然后切换httpService.post 调用,它提供firstService 方法的结果作为第一个参数。

编辑:感谢 JB Nizet,结合了答案的多次迭代:/

【讨论】:

    【解决方案2】:

    在您的情况下,使用哪个组合运算符并不重要:flatMapconcatMapswitchMap;它们的行为相同,因为Angularhttp 只发出一次值并立即完成。

    通常你会更喜欢concatMap,因为这个操作符尊重发射的顺序(这意味着如果你的 Observables 中有一些延迟调用,它们将一个接一个地执行,而 flatMapswitchMap 可以导致不确定的结果,更多细节在这里https://www.baeldung.com/rxjava-flatmap-switchmap)。


    TLDR;使用concatMap

    this.http.get('one').pipe(
      concatMap(result => this.http.get('two'))
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-12
      • 2016-09-12
      • 2022-08-19
      • 1970-01-01
      相关资源
      最近更新 更多