为什么需要将管道与shareReplay一起使用?

时间:2019-10-18 03:55:26

标签: rxjs

我很困惑为什么以下内容无法编译:


login(email: string, password: string): Observable<any> {
    return this.http.post<authObj>('/users/login',{"email": email, "password": password})
    .shareReplay()
  }

(我收到错误Property 'shareReplay' does not exist on type 'Observable<authObj>'.ts(2339))。 供参考的注释:authObj是:

interface authObj {
  "username": string,
  "email": string
} 

但是以下代码可以正常编译:

login(email: string, password: string): Observable<any> {
    return this.http.post<authObj>('/users/login',{"email": email, "password": password})
      .pipe(
        tap(res=> this.setSession),      
        shareReplay()
      );
  }

shareReplay的角度来看,我认为这两种构造在调用对象/输入方面都是相似/相同的,因此我认为上述两种方法都应该起作用。为什么只编译第二个构造?谢谢!

1 个答案:

答案 0 :(得分:3)

从RxJs 5到6的最大变化是树的可摇性。在RxJ 5中,所有运算符都属于可观察类。这意味着,当您将Observable类导入到项目中时,无论是否使用它们,每个操作员都会得到很多。即使您只需要少量的RxJs功能,这也会使应用程序的大小膨胀。

使用RxJs 6时,运算符被移到了可传递的函数中,这意味着您不再能够使用这些方法的流利语法,但是具有巨大的构建优势,只需要包括所需的功能而不是全部功能即可。 RxJs。这样可以大大减少构建的大小。

有关更多信息,请查看: