Angular RxJS-行为子对象,未调用onComplete

Angular RxJS-行为子对象,未调用onComplete,angular,typescript,rxjs,behaviorsubject,Angular,Typescript,Rxjs,Behaviorsubject,我正在构建一个Angular 7应用程序,并使用BehaviorSubject来保持用户身份验证状态,就像在互联网上的每个源上推荐的那样 既然BehaviorSubject是一个可观察的对象,为什么我不能启动onComplete()方法呢 下面是代码(我觉得它很经典): 授权服务 authenticationState = new BehaviorSubject(false); 未记录“完成”。我做错什么了吗 解决方案 this.authService.authenticationState.

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

既然BehaviorSubject是一个可观察的对象,为什么我不能启动onComplete()方法呢

下面是代码(我觉得它很经典):

授权服务

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部分时,可以像这样触发complete

authenticationState.complete();

complete
仅在完成可观察项时调用。这是非错误观测到的最后一个事件

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

authenticationState.first().subscribe();
这样,
complete
将在单个发出的项之后调用

authenticationState.first().subscribe();