Angular 2 从服务获取 Google 身份验证状态

Angular 2 getting the Google Authentication status from a service

我使用 Google 身份验证成功登录和注销,但我的身份验证服务未返回登录状态。我试图在我的 Auth Guard 中阅读它以确定我是否应该定向到登录页面。我收到 _googleAuth 未定义 ("TypeError: Cannot read property 'isSignedIn' of undefined") 的错误。

constructor(private router: Router, private _authService: AuthenticationService) {}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
            return this._authService.getAuthenticatedStatusAsObservable()
            .map((result) => { ...

描述性命名的服务方法如下所示:

getAuthenticatedStatusAsObservable(): Observable<boolean>  {
    if(this._googleAuth){
      return Observable.of(this._googleAuth.isSignedIn.get());
    }
    else {return Observable.of(false) }
  }
}

其他服务方式有效。例如,我可以写出用户名。但是,当我尝试将状态(或用户名)作为可观察对象获取时,它不起作用。

为什么构造函数中的身份验证服务不够用?我想我遗漏了一些关于使用 observables 的东西。

loadAuth() 在服务构造函数中被调用:

loadAuth() {
  // attempt to SILENT authorize
  this.gapiLoad
    .load('auth2')
    .switchMap(() => this.authorize())
    .do((googleAuth: gapi.auth2.GoogleAuth) => this.saveGoogleAuth(googleAuth))
    .do((googleAuth: gapi.auth2.GoogleAuth) => this.listenToGoogleAuthSignIn(googleAuth))
    .filter((googleAuth: gapi.auth2.GoogleAuth) => this.isSignedIn())
    .filter((googleAuth: gapi.auth2.GoogleAuth) => this.hasAccessToken(googleAuth))
    .map((googleAuth: gapi.auth2.GoogleAuth) => googleAuth.currentUser.get())
    .subscribe((googleUser: gapi.auth2.GoogleUser) => {
      this.zone.run(() => this.handleSuccessLogin(googleUser));
    });
  }

检查您的代码何时初始化 gapi.auth2。

这是您检查 Google 身份验证登录状态所需要的。

var result = false;
gapi.load('auth2', function() {
    //gapi.auth2.init(authOptions); // if you haven't initialized yet
    //get instance with client ID, must be called after gapi.auth2.init
    var googleAuthTest = gapi.auth2.getAuthInstance();
    result = googleAuthTest.isSignedIn.get();
});