我一直在try 在angular 2中的一个单独的登录组件中实现Google登录.我无法用Google https://developers.google.com/identity/sign-in/web/sign-in中提供的文档实现它

当我在索引中声明脚本标记和谷歌回调函数时,谷歌登录确实有效.html文件.但我需要一个单独的组件,以便能够使用google按钮呈现登录,并在其中接收回调,以进一步处理为用户接收的访问令牌

推荐答案

在app index.html文件中添加此行

指数html

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

组成部分ts文件

declare const gapi: any;
  public auth2: any;
  public googleInit() {
    gapi.load('auth2', () => {
      this.auth2 = gapi.auth2.init({
        client_id: 'YOUR_CLIENT_ID.apps.googleusercontent.com',
        cookiepolicy: 'single_host_origin',
        scope: 'profile email'
      });
      this.attachSignin(document.getElementById('googleBtn'));
    });
  }
  public attachSignin(element) {
    this.auth2.attachClickHandler(element, {},
      (googleUser) => {

        let profile = googleUser.getBasicProfile();
        console.log('Token || ' + googleUser.getAuthResponse().id_token);
        console.log('ID: ' + profile.getId());
        console.log('Name: ' + profile.getName());
        console.log('Image URL: ' + profile.getImageUrl());
        console.log('Email: ' + profile.getEmail());
        //YOUR CODE HERE


      }, (error) => {
        alert(JSON.stringify(error, undefined, 2));
      });
  }

ngAfterViewInit(){
      this.googleInit();
}

模板html文件

<button id="googleBtn">Google</button>

Plunker上观看演示

Typescript相关问答推荐

具有条件通用props 的react 类型脚本组件错误地推断类型

具有映射返回类型的通用设置实用程序

如何基于对象关键字派生类型?

在TypeScript中使用泛型的灵活返回值类型

在配置对象上映射时,类型脚本不正确地推断函数参数

如何通过TypeScript中的工厂函数将区分的联合映射到具体的类型(如类)?

如何推断计算逻辑的类型

在不更改类型签名的情况下在数组并集上映射文字

为什么不能使用$EVENT接收字符串数组?

记录键的泛型类型

迭代通过具有泛型值的映射类型记录

AngularJS服务不会解析传入的Json响应到管道中的模型

在排版修饰器中推断方法响应类型

React router 6(数据路由)使用数据重定向

带投掷的收窄类型

TypeScrip:如何缩小具有联合类型属性的对象

创建一个函数,该函数返回一个行为方式与传入函数相同的函数

如何实现允许扩展泛型函数参数的类型

TypeScript是否不知道其他函数内部的类型判断?

为什么我无法在 TypeScript 中重新分配函数?