将一个可观察的输出用作角度的另一个输入的正确方法是什么

问题描述 投票:0回答:2

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

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

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);
angular asynchronous rxjs observable
2个回答
3
投票

导入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
}

这是执行您的firstService方法所返回的Observable<item>的所有内容,然后switches转到httpService.post调用,该调用将提供firstService方法的结果作为第一个参数。

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


1
投票

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

通常,您更希望使用concatMap,因为此运算符会遵守发射顺序(这意味着,如果您在Observable中有一些延迟的调用,它们将被依次执行,而flatMapswitchMap可以导致不确定的结果,请点击https://www.baeldung.com/rxjava-flatmap-switchmap了解更多详细信息。


TLDR;使用concatMap

this.http.get('one').pipe(
  concatMap(result => this.http.get('two'))
)
© www.soinside.com 2019 - 2024. All rights reserved.