Sunday, May 22, 2016

'init' of undefined when using gapi with angular

This can be solved by calling gapi.auth2.init in window.gapi_onload and loading google api js through javascript, as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
export class AppComponent implements OnInit {
    ngOnInit() {
        const gappClientId = "xxxxxx.apps.googleusercontent.com";

        window.gapi_onload = function () {
            console.log("gapi onload called");
            var auth2 = gapi.auth2.init({
                client_id: gappClientId,
                scope: 'profile'
            });
        };
        var po = document.createElement('script');
        po.type = 'text/javascript';
        po.async = true;
        po.src = 'https://apis.google.com/js/auth2.js';

        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(po, s);

    }
}

No comments:

Post a Comment