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

问题描述 投票:2回答:2

我想在我的角度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 >
angular typescript google-contacts
2个回答
2
投票

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

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

将gapi类型添加到项目中

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

在您的组件中,

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

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

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

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


0
投票

对于上述解决方案..

ngOnInit(){}服务包括authConfig包括来自包括

© www.soinside.com 2019 - 2024. All rights reserved.