【问题标题】:TypeError: Cannot read property 'http' of undefined angular 2TypeError:无法读取未定义角度 2 的属性“http”
【发布时间】:2017-04-03 21:42:03
【问题描述】:

在我的 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”值无法识别。

我在这里缺少什么?

【问题讨论】:

  • 你有一个函数:function(resp),它正在改变你的this,你期望从课堂上得到的那个。使用箭头函数。

标签: angular typescript angular-promise


【解决方案1】:

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

改用箭头函数:

then((resp) => {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-16
    相关资源
    最近更新 更多