【问题标题】:Handle condition within Pipe RxJS在 Pipe RxJS 中处理条件
【发布时间】:2021-11-30 00:03:31
【问题描述】:

我有这种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) },
          };
        }
      });

【问题讨论】:

    标签: angular typescript ionic-framework rxjs


    【解决方案1】:

    map算子里面的条件怎么样?

    this.leadChanged$ = this.leadsDataService.leadChanged$.pipe(
      map(res => res?.isManualLead
        ? { ...res } 
        : { ...res, alert: { ...res.alert, transcript: highlightKeywordsLeadFunction(this.lead) } }
      ),
    );
    

    【讨论】:

      【解决方案2】:

      您可以根据条件 sing 订阅第一个或第二个 observable iifrxjs 算子

      import { iif, of } from 'rxjs';
      import { mergeMap } from 'rxjs/operators';
      ...
      
      this.leadsDataService.leadChanged$.pipe(
        mergeMap((res) => iif(() => res?.isManualLead, of({ ...res }), of(anotherValue)))
      );
      

      【讨论】:

        猜你喜欢
        • 2021-02-18
        • 1970-01-01
        • 2021-06-07
        • 2020-07-17
        • 1970-01-01
        • 1970-01-01
        • 2021-09-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多