angular2-google-login
v1.0.9
Published
Google login with Angular 2
Downloads
125
Maintainers
Readme
Angular 2 Google Login
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
To use the package in your app
Run npm install angular2-google-login
Import Package
Import this package where you want to use Google authentication service.
import { AuthService, AppGlobals } from 'angular2-google-login';
Providers
Supply the provider.
providers: [AuthService];
Constructor
constructor(private _googleAuth: AuthService){}
Set your Secret Google Client ID
Set your Google client Id. preferably in ngOnInit()
interface.
AppGlobals.GOOGLE_CLIENT_ID = 'SECRET_CLIENT_ID';
Using the Google Login service
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
});
Using fetched Google account details
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;
Logout user
this._googleAuth.userLogout(()=>{
//YOUR_CODE_HERE
});
Development server
Run ng serve
for a dev server. Navigate to http://localhost:4200/
.
Known Issue
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.