I have been trying to implement sign in with Google in angular 2 in a separate login component. I am unable to implement it with the documentation available in Google https:
Lexical scoping with an arrow (=>) function makes the use of let that = this; unnecessary.
A cleaner version of Pravesh's example, without the need for the that scoping work-around, would be:
Index.html
<script src="https://apis.google.com/js/platform.js" async defer></script>
Component.ts
declare const gapi: any;
@Component({
selector: 'google-signin',
template: '<button id="googleBtn">Google Sign-In</button>'
})
export class GoogleSigninComponent implements AfterViewInit {
private clientId:string = 'YOUR_CLIENT_ID.apps.googleusercontent.com';
private scope = [
'profile',
'email',
'https://www.googleapis.com/auth/plus.me',
'https://www.googleapis.com/auth/contacts.readonly',
'https://www.googleapis.com/auth/admin.directory.user.readonly'
].join(' ');
public auth2: any;
public googleInit() {
gapi.load('auth2', () => {
this.auth2 = gapi.auth2.init({
client_id: this.clientId,
cookiepolicy: 'single_host_origin',
scope: this.scope
});
this.attachSignin(this.element.nativeElement.firstChild);
});
}
public attachSignin(element) {
this.auth2.attachClickHandler(element, {},
(googleUser) => {
let profile = googleUser.getBasicProfile();
console.log('Token || ' + googleUser.getAuthResponse().id_token);
console.log('ID: ' + profile.getId());
// ...
}, function (error) {
console.log(JSON.stringify(error, undefined, 2));
});
}
constructor(private element: ElementRef) {
console.log('ElementRef: ', this.element);
}
ngAfterViewInit() {
this.googleInit();
}
}
Template
<div id="googleBtn">Google</div>
Working Plnkr