简体   繁体   中英

How to get correct method scope using Google signin with angular project

I am 95% of the way to getting google signin to work. Trying to figure out 2 problems with the code. Here is my current code (simplified)

loginWithGoogle(): void {
  //this one works
  google.accounts.id.initialize({
    client_id: 'appid.apps.googleusercontent.com',
    callback: this.handleCredentialResponse
  });
  google.accounts.id.prompt();
}

handleCredentialResponse(response: any) {
  //makes it here
  this.processLogin(response);
}

processLogin(response: any) {
  //doesn't make it here
}

Problem #1: When google.accounts.id.initialize fails, I can see the error on the console log, but how do I get that error in my code? I feel like I need some kind of error callback, but none is shown in the documentation. Is there now way to get that error message?

Problem #2: callback works great getting me to handleCredentialResponse, but then the "this" is no longer in the correct scope, so it cannot make it to the next method. How can I structure this to maintain the correct angular scope?

getting: TypeError: this.authorizedLogin is not a function. error.

I was able to get this to work by using ngZone:

  google.accounts.id.initialize({
    client_id: "appId.apps.googleusercontent.com",
    callback: (window as any)['handleCredentialResponse'] =
      (response: any) => this.ngZone.run(() => {
        this.handleCredentialResponse(response);
      })
  });
  google.accounts.id.prompt();

As for the error message, it appears there is no solution and likely google simply forgot to provide an error callback method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM