在 Pipe RxJS 中处理条件
Handle condition within Pipe RxJS
我有这种 Observable
,我可以很容易地使用模板上的 async
管道。
leadChanged$: Observable<LeadModel>;
this.leadChanged$ = this.leadsDataService.leadChanged$.pipe(
map((res) => ({
...res,
alert: { ...res.alert, transcript: highlightKeywordsLeadFunction(this.lead) },
}))
);
但是由于额外的逻辑,现在我需要这样写:逻辑是这样的res?.isManualLead
。你知道如何在没有 subscribe
的情况下使用它吗?即我也想在这里使用 async
管道。
leadChanged: LeadModel;
this.leadsDataService.leadChanged$
.subscribe((res) => {
if (res?.isManualLead) {
this.leadChanged = {
...res,
};
} else {
this.leadChanged = {
...res,
alert: { ...res.alert, transcript: highlightKeywordsLeadFunction(this.lead) },
};
}
});
map算子里面的condition怎么样?
this.leadChanged$ = this.leadsDataService.leadChanged$.pipe(
map(res => res?.isManualLead
? { ...res }
: { ...res, alert: { ...res.alert, transcript: highlightKeywordsLeadFunction(this.lead) } }
),
);
您可以根据条件订阅第一个或第二个可观察对象
iif rxjs 运算符
import { iif, of } from 'rxjs';
import { mergeMap } from 'rxjs/operators';
...
this.leadsDataService.leadChanged$.pipe(
mergeMap((res) => iif(() => res?.isManualLead, of({ ...res }), of(anotherValue)))
);
我有这种 Observable
,我可以很容易地使用模板上的 async
管道。
leadChanged$: Observable<LeadModel>;
this.leadChanged$ = this.leadsDataService.leadChanged$.pipe(
map((res) => ({
...res,
alert: { ...res.alert, transcript: highlightKeywordsLeadFunction(this.lead) },
}))
);
但是由于额外的逻辑,现在我需要这样写:逻辑是这样的res?.isManualLead
。你知道如何在没有 subscribe
的情况下使用它吗?即我也想在这里使用 async
管道。
leadChanged: LeadModel;
this.leadsDataService.leadChanged$
.subscribe((res) => {
if (res?.isManualLead) {
this.leadChanged = {
...res,
};
} else {
this.leadChanged = {
...res,
alert: { ...res.alert, transcript: highlightKeywordsLeadFunction(this.lead) },
};
}
});
map算子里面的condition怎么样?
this.leadChanged$ = this.leadsDataService.leadChanged$.pipe(
map(res => res?.isManualLead
? { ...res }
: { ...res, alert: { ...res.alert, transcript: highlightKeywordsLeadFunction(this.lead) } }
),
);
您可以根据条件订阅第一个或第二个可观察对象 iif rxjs 运算符
import { iif, of } from 'rxjs';
import { mergeMap } from 'rxjs/operators';
...
this.leadsDataService.leadChanged$.pipe(
mergeMap((res) => iif(() => res?.isManualLead, of({ ...res }), of(anotherValue)))
);