This is a sample app showing how we can login using Google authentication in Angular2.
You can visit npm for more info on angular2-google-login package
[]() []() []() []()
Run npm install angular2-google-login
Import this package where you want to use Google authentication service.
import { AuthService, AppGlobals } from 'angular2-google-login';
Supply the provider.
providers: [AuthService];
constructor(private _googleAuth: AuthService){}
Set your Google client Id. preferably in ngOnInit()
interface.
AppGlobals.GOOGLE_CLIENT_ID = 'SECRET_CLIENT_ID';
Use this code snippet to call the Google authentiation service. You can call it in a function triggered by a button click or in your desired event.
this._googleAuth.authenticateUser(()=>{
//YOUR_CODE_HERE
});
In the package, localstorage
is used to hold the data -
localStorage.setItem('token', userDetails.getAuthResponse().id_token);
localStorage.setItem('image', profile.getImageUrl());
localStorage.setItem('name', profile.getName());
localStorage.setItem('email', profile.getEmail());
Alternatively, you can tweak the code and create an object that you can return to do post operation after successful login -
result = {
token: userDetails.getAuthResponse().id_token,
name: profile.getName(),
image: profile.getImageUrl(),
email: profile.getEmail(),
};
return result;
this._googleAuth.userLogout(()=>{
//YOUR_CODE_HERE
});
Run ng serve
for a dev server. Navigate to http://localhost:4200/
.
You might get error : gapi is not defined
It is because the service component may get loaded before gapi
is declared. Make sure you handle it when you use the service.
SUGGESTION : Use AfterViewInit
interface.