【问题标题】:How to chain one observable , one regular sync function and another observable at the end如何在最后链接一个 observable、一个常规同步函数和另一个 observable
【发布时间】:2020-11-13 16:15:53
【问题描述】:

我想利用pipe 命令和来自一个可观察对象的链接,处理订阅中的输出数据,然后运行一个函数来转换数据,然后将结果输入到一个新的可观察函数。我试图将函数与管道和switchMap 链接,但我不确定如何提升并能够插入 2 个 observables 之间的转换函数

service.FirstFunction().pipe( 
     switchMap((info) => this.Transform(info),switchMap((data) => service.secondFunction(data))
 )
.subscription((x)=> this.Updatedata(x));

this.transform 是常规函数,不是可观察的

谢谢

沃利

【问题讨论】:

    标签: javascript angular typescript rxjs


    【解决方案1】:

    看起来this.Transform 没有返回可观察对象,所以这里不需要switchMap。你可以改用map

    service.FirstFunction().pipe( 
      map((info) => this.Transform(info),
      switchMap((data) => service.secondFunction(data))
    ).subscribe((x)=> this.Updatedata(x));
    

    另外,你可以通过传入函数来简化代码:

    service.FirstFunction().pipe( 
      map(this.Transform.bind(this)),
      switchMap(service.secondFunction.bind(service))
    ).subscribe(this.Updatedata.bind(this));
    

    你必须绑定,因为函数绑定到一个对象。如果函数中没有使用 this 你可以跳过绑定工作。

    顺便说一句,为了简化订阅工作,您还可以在此处使用点击:

    service.FirstFunction().pipe( 
      map(this.Transform.bind(this)),
      switchMap(service.secondFunction.bind(service)),
      tap(this.Updatedata.bind(this))
    ).subscribe();
    

    【讨论】:

      【解决方案2】:

      你已经接近了。您不需要第一个 switchMap 来转换数据。它可以在单个 switchMap 内完成。

      service.FirstFunction().pipe(
        switchMap(info => service.secondFunction(this.Transform(info)))
      ).subscription(
        (x) => this.Updatedata(x)
      );
      

      【讨论】:

      • 谢谢,我现在就测试一下,为什么有时候 this 是未定义的?
      • 您需要使用bind(this) 绑定它或使用此处的箭头函数。您可以通过here了解更多信息。
      猜你喜欢
      • 1970-01-01
      • 2020-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-18
      相关资源
      最近更新 更多