如何使switchmap返回值来自早期可观察的
我有一个可观察到的正在获取客户信息的可观察,我想使用客户编号查找
我需要的名称。WorkDetail$包含GetWorkItem的两个响应,这是一个可能包含客户编号的JSON对象,如果确实如此我想查找它,并将客户名称添加到可观察到的输出中,
this.workDetail$ = this.workService
.getWorkItem(workNumber)
.pipe(
iif((res: WorkItemNumberResposne) => res.customerNumber),
//want this customer number added to main output stream
this.customerService.getCustomerById(res.customerNumber),
//else nothing to do
);
即使是正确的方法?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我们可以使用
switchmap
this.customerService.getCustomerById(res.customernumber)
将返回。我们使用iif()
https:htttps:htttps:// wwwww。 Learnrxjs.io/learn-rxjs/operators/conditional/iif 操作员要比较,res?.customernumber!= null ||未定义的
,基于这种情况,我们将返回trueresult
或falseresult
。随意自己进行替换并消除延迟。
工作示例:
We could use
switchMap
https://www.learnrxjs.io/learn-rxjs/operators/transformation/switchmap operator to take valueres
fromthis.workService.getWorkItem(workNumber)
and then switch tothis.customerService.getCustomerById(res.customerNumber)
which will be returned instead. We useiif()
https://www.learnrxjs.io/learn-rxjs/operators/conditional/iif operator to compare, thatres?.customerNumber != null || undefined
and based on this condition we will return eithertrueResult
orfalseResult
.Feel free to make substitutions yourself and remove the delay.
Working example: https://stackblitz.com/edit/angular-ivy-8b33tr?file=src%2Fapp%2Fapp.component.ts
根据条件,请返回可观察的或另一个。您的病情是关于对可观察的响应的响应,因此我们需要使用swichmap(您将可观察到的“ workdetail”切换到可观察到的“ iif”),
如果条件已充满了状态,您可以返回可观察到的“ this.customerService.getCustomerById(res.customernumber)”,但是您转换(使用映射)以返回具有FISRT可观察的属性以及此上次可观察的属性的属性(为此,我使用传播操作员,如果只想添加新属性,您可以使用一些像
{ ... res,自定义名称:customer.name}
在代码中
iif return an observable or another one according to a condition. Your condition is about the response to an observable so we need use swichMap (you switch the observable "workDetail" to the observable "iif")
If condition is fullfilled you return the observable "this.customerService.getCustomerById(res.customerNumber)", but you transform (using map) to return an object with the properties of the fisrt observable plus the properties of this last Observable (for this I use spread operator, if only want to add a new property you can use some like
{...res,customerName:customer.name}
In code