网站搜索

angular - RxJS - BehaviorSubject,onComplete 未被调用


我正在构建一个 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);

‘complete’ 没有被记录。我是不是做错了什么?

解决方案

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

然后 complete() 方法被触发

答案#1

complete 只有在 Observable 完成发出项目时才会被调用。换句话说,它是来自非错误 Observable 的最后一个事件。

如果你只对这个可观察对象中的单个项目感兴趣,你可以:

authenticationState.first().subscribe();

这样,complete 将在单个发出的项之后被调用。

答案#2

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

authenticationState.complete();