TypeError: Cannot read property 'http' of undefined angular 2

TypeError: Cannot read property 'http' of undefined angular 2

在我的 Angular 2 应用程序中成功实现 gapi 客户端后,我现在遇到了一个问题,即我的 http 对象未定义,我不确定为什么。

代码如下: 构造函数(私有 http: Http){}

initGmailApi() {

gapi.auth2.getAuthInstance().grantOfflineAccess().then(function(resp) {
    console.log(resp);
    const auth_code = resp.code;

    const body = {'AuthCode': auth_code};
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    this.http.post('http://localhost:8080/startgmail', body,  headers).subscribe(
    (Response) => {
        console.log(Response);
    }
    );
});
}

基本上我正在做的是请求用户访问他的 gmail 帐户的权限,当我收到回复时,我想将收到的一些数据传递到我的后端服务器。

如果我在 "then" 子句之外使用 this.http,则 http 方法可以正常工作,但这会产生另一个问题,即无法识别 "auth_code" 值。

我在这里错过了什么?

如果您想在回调中引用 this,请不要使用 function() {}

改用箭头函数:

then((resp) => {