如何获得角度2的谷歌联系人

时间:2017-02-10 10:37:55

标签: angular typescript google-contacts

我想在我的角度2项目中获取谷歌联系人 这是我的代码,请帮助我,提前谢谢。 在组件中我做到了这一点:

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" )
                )
        }

在服务中我这样做了:

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);
    }

并在html中:

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

2 个答案:

答案 0 :(得分:2)

这就是我在Angular4中使用它的方法。首先,您需要在index.html中包含Google API脚本:

isinstance

将gapi类型添加到项目中

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

在您的组件中,

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

不要忘记导入gapi类型,否则你会得到gapi未定义的错误;

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);
          }
        }
      )
  }
}

此外,如果您使用Chrome,则可能需要允许来自应用程序域的弹出式窗口,否则Google API身份验证将无法继续。请参阅stackoverflow上的this question

答案 1 :(得分:0)

上述解决方案。

ngOnInit(){}中的服务包含authConfig中的包,其中包含

相关问题