Angular 6 Import google contacts

Gautier
Apparence.io
Published in
2 min readJul 6, 2017
“A black phone in a red vintage phone box” by Antoine Barrès on Unsplash

Google provides tons of api, but sometimes their documentations lacks of updates. Other thing is, it seems that they provide some duplicate api (people api and contacts api… just hard to find the small differences, and it seems that contacts is going to die…).

This article will just show how to use google people api to fetch user email from his google contacts list using Angular 4.

Lets see how we gonna do this

1 Connect with our google account

2 ask for the “scopes” that we are going to need

3 ask google the contact of the user

4 do what (you have to do) with thoses emails

1 — Import javascript libraries

inside your index.html and at the en of the body tag

<script async defer src="https://apis.google.com/js/platform.js"></script>
<script async defer src="https://apis.google.com/js/api.js"></script>

2 — initiate you component

create your component and initiate your import of the api. Outside of you component code :

declare var gapi: any;

then you got to load the api like this :

ngAfterViewInit(): void {
setTimeout(() => this.signIn(), 1000);
}


signIn() {
gapi.load('auth2', () => {
this.auth2 = gapi.auth2.init({
client_id: 'YOUR_CLIENT_ID',
cookie_policy: 'single_host_origin',
scope: 'profile email https://www.googleapis.com/auth/contacts.readonly'
});
this.auth2.attachClickHandler(document.getElementById('googleres'), {}, this.onSignIn, this.onFailure);
})
}

the reason of the setTimeOut is simply to avoid try to load gapi before the api is completely downloaded. 1 second seems enough.

Replace YOUR_CLIENT_ID with the one you create in google developper console / web oauth credential.

See here we now have our button linked to our google Auth2 object, this means that we gonna be logged in when we click on it.

3— On sign in and fetch emails

when user accept this is what we want to do :

onSignIn = (data: any) => {

setTimeout(() => this.fetchmail(), 1000);
}

data is containing our token

fetchmail() {
gapi.load('client:auth2', () => {
gapi.client.init({
apiKey: 'API_KEY use your own',
discoveryDocs: ['https://people.googleapis.com/$discovery/rest?version=v1'],
clientId: 'YOUR_CLIENT_ID',
scope: 'profile email https://www.googleapis.com/auth/contacts.readonly'
}).then(() => {
return gapi.client.people.people.connections.list({
resourceName:'people/me',
personFields: 'emailAddresses,names'
});
}).then(
(res) => {
//console.log("Res: " + JSON.stringify(res)); to debug
this.userContacts.emit(this.transformToMailListModel(res.result));
},
error => console.log("ERROR " + JSON.stringify(error))
);
});

now you have the users mailing list with names. Simple as that.

Enjoy,

--

--