【问题标题】:Angular 2 getting the Google Authentication status from a serviceAngular 2 从服务获取 Google 身份验证状态
【发布时间】:2017-11-19 16:17:11
【问题描述】:

我已使用 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) }
  }
}

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

为什么在构造函数中没有足够的身份验证服务?我想我错过了一些关于使用 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));
    });
  }

【问题讨论】:

  • 显示你是如何初始化this._googleAuth的?
  • @RomanC 添加了它。谢谢
  • 前三行某处出现故障,您应该调试。抱歉,这是题外话

标签: angular google-api angular2-services google-authentication


【解决方案1】:

检查您的代码何时初始化 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();
});

【讨论】:

  • 你是对的。我的代码正在为登录初始化 gapi.auth2,但后来我没有使用 GetAuthInstance。对于任何阅读本文的人来说,唯一的问题是你不能将它初始化两次。您将收到“已使用不同选项初始化”的错误消息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-11
  • 1970-01-01
  • 1970-01-01
  • 2017-05-09
  • 2017-01-13
  • 1970-01-01
  • 2017-02-24
相关资源
最近更新 更多