我正在构建一个 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() 方法被触发
最佳答案
complete
仅当 Observable 完成发射项时才会被调用。 IOW,这是来自无错误 Observable 的最后一个事件。
如果您只对此 Observable 中的单个项目感兴趣,您可以:
authenticationState.first().subscribe();
这样,complete
将在单个发出的项目之后被调用。
关于angular - RxJS -BehaviorSubject,onComplete 未调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56146574/