Naresh Kotha
Naresh Kotha

Reputation: 79

how to get google contacts in angular 2

i am trying to get google contacts in my angular 2 project here is my code please help me, thanks in advance. in component i done this:

googleContacts(){
        this.contactService.googleLogin()
        .subscribe(
                response => {
                    this.logger.info("addContactComponent googleContacts(): "+ response);
                    window.location.href = ""+ response; 

                },
                error => this.logger.error( error ),
                () => this.logger.info( "google_contacts() finished" )
                )
        }

and in service i done like this:

googleLogin():Observable<Response> {
       this.logger.info(this.googleContactsUrl+"authorizeLogin?access_token=" + this.authenticationService.access_token);
        return this._http.get(this.googleContactsUrl+"authorizeLogin?access_token=" + this.authenticationService.access_token)
        .map((response: any) => response);
    }

and in html:

<button style="margin: -8px; background-color: white" (click) = "googleContacts()"></button >

Upvotes: 3

Views: 2078

Answers (2)

pratik pawar
pratik pawar

Reputation: 11

for above mentioned solutions..

in ngOnInit(){} the service included authConfig which package from include

Upvotes: 0

Terence Monteiro
Terence Monteiro

Reputation: 21

This is how I got it working in Angular4. First, you need to include the Google API scripts in your index.html:

  <script src="https://apis.google.com/js/platform.js"></script>
  <script src="https://apis.google.com/js/client.js"></script>

Add the gapi types into your project

npm install --save @types/gapi
npm install --save @types/gapi.auth2

In your component,

ngOnInit() {
  this.authConfig = {
    client_id: '<YOUR-CLIENT-ID>',
    scope: 'https://www.googleapis.com/auth/contacts.readonly'
  };
}

googleContacts() {
  gapi.client.setApiKey('<YOUR-API-KEY>');
  gapi.auth2.authorize(this.authConfig, this.handleAuthorization);
}

handleAuthorization = (authorizationResult) => {
  if (authorizationResult && !authorizationResult.error) {
    let url: string = "https://www.google.com/m8/feeds/contacts/default/thin?" +
       "alt=json&max-results=500&v=3.0&access_token=" +
       authorizationResult.access_token;
    console.log("Authorization success, URL: ", url);
    this.http.get<any>(url)
      .subscribe(
        response => {
          if (response.feed && response.feed.entry) {
            console.log(response.feed.entry);
          }
        }
      )
  }
}

Don't forget to import gapi types as otherwise you'll get gapi undefined errors;

import { } from '@types/gapi';
import { } from '@types/gapi.auth2';

Also, if you're using Chrome, you may need to allow popups from your application domain, otherwise the Google API authentication will not be able to proceed. See this question on stackoverflow.

Upvotes: 2

Related Questions