【问题标题】:RxJS - BehaviorSubject, onComplete not calledRxJS - BehaviorSubject,onComplete 未调用
【发布时间】:2019-10-02 10:25:35
【问题描述】:

我正在构建一个 Angular 7 应用程序并使用 BehaviorSubject 来保持用户身份验证状态,正如互联网上每个来源所推荐的那样。

既然 BehaviorSubject 是一个 Observable,为什么我不能触发 onComplete() 方法?

这是代码(我觉得这很经典):

this.authService.authenticationState.subscribe(state => {
      this.isLoggedIn = state;
    },
    err => console.log(err),
    () => console.log('complete')
    );

身份验证服务

authenticationState = new BehaviorSubject(false);

“完成”未记录。是不是我做错了什么?

解决方案

this.authService.authenticationState.subscribe(state => {
      this.isLoggedIn = state;
      this.authService.authenticationState.complete();
    },
    err => console.log(err),
    () => console.log('complete')
    );

然后触发 complete() 方法

【问题讨论】:

    标签: angular typescript rxjs behaviorsubject


    【解决方案1】:

    complete 仅在 Observable 完成发射项目时调用。 IOW 这是来自非错误 Observable 的最后一个事件。

    如果您只对此 Observable 中的单个项目感兴趣,您可以:

    authenticationState.first().subscribe();
    

    这样complete 将在单个发射项目之后被调用。

    【讨论】:

      【解决方案2】:

      我认为当您准备好调用订阅的完整部分时,您可以像这样触发完成。

      authenticationState.complete();
      

      【讨论】:

        猜你喜欢
        • 2017-05-04
        • 2016-11-07
        • 2021-04-19
        • 2019-09-24
        • 1970-01-01
        • 2020-09-27
        • 1970-01-01
        • 2018-08-31
        • 1970-01-01
        相关资源
        最近更新 更多