Angular13集成Google Identity Services时遇函数调用错误
解决Angular 13中Google Identity Services回调函数无法访问组件方法的问题
问题根源
当你将handleCredentialResponse作为回调函数传入google.accounts.id.initialize时,函数的this上下文会丢失,不再指向当前组件实例,导致调用this.getUserData时提示“不是函数”。
解决方案
以下三种方法都能修复这个问题,任选其一即可:
方法1:用箭头函数包装回调
在初始化配置中,用箭头函数包裹回调函数,箭头函数会自动继承当前组件的this上下文:
google.accounts.id.initialize({ client_id: clientId, callback: (response) => this.handleCredentialResponse(response) });
方法2:在构造函数中绑定this
在组件的构造函数里,将handleCredentialResponse的this绑定到组件实例,确保无论函数在哪里调用,this始终指向组件:
constructor() { this.handleCredentialResponse = this.handleCredentialResponse.bind(this); }
之后初始化代码中的回调可以保持原样:
google.accounts.id.initialize({ client_id: clientId, callback: this.handleCredentialResponse });
方法3:将回调函数改为箭头函数形式
直接把handleCredentialResponse定义为箭头函数,这样它的this会永久绑定到组件实例:
handleCredentialResponse = (response) => { var base64Url = (response.credential).split('.')[1]; var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/'); var jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function(c) { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); }).join('')); const responsePayload = JSON.parse(jsonPayload); let user : any = { id : responsePayload.sub, name : responsePayload.name, email : responsePayload.email, photoUrl : responsePayload.picture, firstName : responsePayload.given_name, lastName : responsePayload.family_name, provider : 'GOOGLE' } this.getUserData(user); }
内容的提问来源于stack exchange,提问作者Lakhvir Singh
相关产品推荐
相关产品推荐

