首页 > 解决方案 > 在 Angular 中使用 google 登录时出现 attachClickHandler 错误

问题描述

我正在尝试在我的 Angular 项目中使用 google 实现社交登录

这是我的相关登录 html 代码

 <button (click)="prepareLoginButton()" #googleSignUp >Login Using Google</button>

这是我相关的 ts 代码

export class LoginComponent implements OnInit {
    
    @ViewChild('googleSignUp', { static: true })
    googleSignUp: ElementRef;
    
    auth2: any;
    ngOnInit(): void {
        this.googleSDK();
    }
    //google login
    prepareLoginButton() {
        this.auth2.attachClickHandler(
            this.googleSignUp.nativeElement,
            {},
            (googleUser) => {
                let profile = googleUser.getBasicProfile();
                this.socialLogin.id = profile.getId();
                this.socialLogin.fullName = profile.getName();
                this.socialLogin.email = profile.getEmail();
                this.socialService.setSocialDetails(this.socialLogin);
            },
            (error) => {
                alert(JSON.stringify(error, undefined, 2));
            }
        );
    }
    googleSDK() {
        window['googleSDKLoaded'] = () => {
            window['gapi'].load('auth2', () => {
                this.auth2 = window['gapi'].auth2.init({
                    client_id: 'xxxxxxxxxxxxx',
                    cookiepolicy: 'single_host_origin',
                    scope: 'profile email'
                });
                this.prepareLoginButton();
            });
        };

        (function(d, s, id) {
            var js,
                fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) {
                return;
            }
            js = d.createElement(s);
            js.id = id;
            js.src = 'https://apis.google.com/js/platform.js?onload=googleSDKLoaded';
            fjs.parentNode.insertBefore(js, fjs);
        })(document, 'script', 'google-jssdk');
    }
}

我已经面对这个错误很长时间了

请告诉如何解决它

这是我得到的错误 在此处输入图像描述

标签: angularoauthgoogle-oauth

解决方案


我不知道这是否对您有帮助,但对于您prepareLoginButton在加载方法中调用的人以及当用户单击按钮时,这可能不是您想要的。

您可以gapi.load从角度调用

declare const gapi: any; //put this ABOVE your @Component (after imports)

private googleSDK() {
    gapi.load('auth2', () => {
      this.auth2 = gapi.auth2.init({
        client_id: environment.googleClientId,
        cookie_policy: 'single_host_origin',
        scope: 'profile email',
      });
      this.prepareLoginButton();
    });
  }

推荐阅读