Search code examples
angularpromiseangular2-templategoogle-oauthgoogle-api-js-client

Template not updated (but model is) after authentication with Google


I have a simple model displaying the email of my user, ang I'm using Google to authenticate.

Here is the code I wrote for authentication:

gapi.auth2.getAuthInstance().signIn().then((args) => {
  this.user = { email: args.wc.hg }
  console.log(this.user);
});

The console.log is correctly displaying the email but the template is not updated and I still see nothing on the browser: {{user?.email}}.

An other point, I just replaced the authentication with a simple promise :

new Promise<string>(resolve => setTimeout(() => resolve('email'), 10000)).then(data => this.user = { email: data });

This is working and my template is displaying email.

I cannot see the difference between the resolution of these two promises, but obviously there is one.

Do you have any idea? Thanks in advance.


Solution

  • That's because code it running out of angular2 framework.What you can do is, you can check change detection manually using below code,

    import { Component, ChangeDetectorRef } from '@angular/core';    
    
    export class MyComponent {
      constructor(private cdr:ChangeDetectorRef) {  //<----- injection
      }
    
      someMethod() {
    
        gapi.auth2.getAuthInstance().signIn().then((args) => {
           this.user = { email: args.wc.hg }
            console.log(this.user);
    
             this.cdr.detectChanges();              //<----Note this...
        });
    
      }
    }