Angular 角型和RxJS受试者头痛伴canActivate

Angular 角型和RxJS受试者头痛伴canActivate,angular,rxjs,subject,Angular,Rxjs,Subject,我得到了一个使用firebase的Angular2项目示例。authService正在使用一个方法IsAuthentified with a subject,该方法返回subject.asObserveable 该方法被调用两次: 在带有subscribe的头组件构造函数中,它将返回值传递给变量 在路由器保护中,第一个()在canActivate中。 示例项目按预期工作 我用我自己的东西在没有FirebaseAPI的情况下重新编写了它,它在header组件中按预期工作,但在router gu

我得到了一个使用firebase的Angular2项目示例。authService正在使用一个方法IsAuthentified with a subject,该方法返回subject.asObserveable

该方法被调用两次:

  • 在带有subscribe的头组件构造函数中,它将返回值传递给变量

  • 在路由器保护中,第一个()在canActivate中。 示例项目按预期工作

我用我自己的东西在没有FirebaseAPI的情况下重新编写了它,它在header组件中按预期工作,但在router guard中,我总是返回一个空对象。如果我像示例项目中那样使用它,路由器将停止工作,因此我对其进行了修改,以查看发生了什么。 这是authService中的代码:

  isAuthenticated() {
const state = new Subject<boolean>();
state.subscribe(x => console.log('Subject start: ' + x));
this.localStorageService.observe('myToken')
  .subscribe((newToken: MyToken) => {
    console.log('localStorageCheck: ' + JSON.stringify(newToken));
    if ((newToken !== null) && (newToken.token !== '')) {
      state.next(true);
    } else {
      state.next(false);
    }
    console.log('state changed');
  });
state.subscribe(x => console.log('Subject subscribe: ' + x));
return state.asObservable();
}

示例项目只有:返回此.authService.isAuthenticated().first(); 我看不出逻辑上有什么不同,我想理解,我在这里遗漏了什么

多谢各位

另外,与防护装置一起工作的代码如下所示:

isAuthenticated() {
const state = new Subject<boolean>();
firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    state.next(true);
  } else {
    state.next(false);
  }
});
return state.asObservable();
isAuthenticated(){
const state=新主题();
firebase.auth().onAuthStateChanged(函数(用户){
如果(用户){
state.next(true);
}否则{
state.next(false);
}
});
返回状态。asObservable();
}

经过更多的测试,我可以观察到,
canActivate
会在我的项目中主题更新后立即运行,而在示例项目中不会发生这种情况(尽管主题也在那里更新)。唯一的区别是,该示例使用Firebase中的observer,而我使用的是ng2 webstorage中的observer。当然,我可以通过在canActivate之外设置一个私有var来解决这个问题,这是可行的


我真的很想了解这种不同行为的原因。希望有人能原谅我,谢谢。

您不仅可以返回布尔值,还可以返回canActivate方法中的Observable或Promise:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.authService.isUserAuthenticated.isAuthenticated();
}
canActivate(路由:ActivatedRouteSnapshot,状态:RouterStateSnashot):可观察{
返回此.authService.isUserAuthenticated.isAuthenticated();
}
我知道;-)当我返回可观察对象时,路由器停止工作。我的基本问题是,尽管在调试器(源代码是主题)中它看起来像是正确的可观察对象,但我如何得到返回的空对象。未调用subscribe。我在工具栏中设置的变量总是得到正确更新。
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.authService.isUserAuthenticated.isAuthenticated();
}