You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular2中Promise回调内无法访问this问题求助

解决Angular中回调函数里无法访问this的问题

哥们,你遇到的这个问题其实一点都不奇怪——这是JavaScript里函数上下文绑定的经典坑,跟Angular本身关系不大~

先给你拆解原因:当你把this.loadGoogleApi直接传给gapi.load当回调时,这个函数的this上下文就跟你的服务实例“解绑”了,执行的时候this指向的是全局对象(浏览器里就是window)或者undefined,自然访问不到你服务里的东西。

给你几个简单有效的解决办法,挑一个顺手的用就行:

方法1:用箭头函数包裹回调

箭头函数会自动继承外部的this上下文,直接把回调包一层就行:

constructor() { 
  gapi.load('client:auth2', () => this.loadGoogleApi()); 
} 

方法2:用bind手动绑定this

在传递函数的时候,用bind把this强制绑定到你的服务实例上:

constructor() { 
  gapi.load('client:auth2', this.loadGoogleApi.bind(this)); 
} 

方法3:提前在构造函数里绑定方法

如果这个方法会被多次用作回调,你可以在构造函数里提前绑定好,后面直接传就行:

constructor() { 
  // 提前绑定this到当前实例
  this.loadGoogleApi = this.loadGoogleApi.bind(this);
  gapi.load('client:auth2', this.loadGoogleApi); 
} 

方法4:用类成员箭头函数定义方法

直接把loadGoogleApi定义成箭头函数,这样它的this会一直指向服务实例:

private loadGoogleApi = () => { 
  // 这里的this就正确指向你的服务啦
  const DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"]; 
  const SCOPES = "https://www.googleapis.com/auth/calendar.readonly"; 
  // 继续你的Google API初始化逻辑...
}

constructor() { 
  gapi.load('client:auth2', this.loadGoogleApi); 
} 

这些方法本质都是确保回调执行时,this能正确指向你的服务实例,随便选一个都能解决问题~

内容的提问来源于stack exchange,提问作者Worthy7

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:55:53