RxJS - BehaviorSubject,未调用 onComplete
RxJS - BehaviorSubject, onComplete not called
我正在构建一个 Angular 7 应用程序并使用 BehaviorSubject 来保持用户身份验证状态,正如互联网上每个来源所推荐的那样。
既然 BehaviorSubject 是一个 Observable,为什么我不能触发 onComplete() 方法?
这是代码(对我来说似乎很经典):
this.authService.authenticationState.subscribe(state => {
this.isLoggedIn = state;
},
err => console.log(err),
() => console.log('complete')
);
authService
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() 方法
我认为当您准备好调用订阅的完整部分时,您可以像这样触发完成。
authenticationState.complete();
complete
仅在 Observable 完成发射项目时调用。 IOW 这是 non-erroneous Observable 的最后一个事件。
如果您只对此 Observable 中的单个项目感兴趣,您可以:
authenticationState.first().subscribe();
这样 complete
将在单个发出的项目之后被调用。
我正在构建一个 Angular 7 应用程序并使用 BehaviorSubject 来保持用户身份验证状态,正如互联网上每个来源所推荐的那样。
既然 BehaviorSubject 是一个 Observable,为什么我不能触发 onComplete() 方法?
这是代码(对我来说似乎很经典):
this.authService.authenticationState.subscribe(state => {
this.isLoggedIn = state;
},
err => console.log(err),
() => console.log('complete')
);
authService
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() 方法
我认为当您准备好调用订阅的完整部分时,您可以像这样触发完成。
authenticationState.complete();
complete
仅在 Observable 完成发射项目时调用。 IOW 这是 non-erroneous Observable 的最后一个事件。
如果您只对此 Observable 中的单个项目感兴趣,您可以:
authenticationState.first().subscribe();
这样 complete
将在单个发出的项目之后被调用。