【问题标题】:How to access class variable inside Promise then() function? [duplicate]如何访问 Promise then() 函数中的类变量? [复制]
【发布时间】:2018-06-12 08:39:52
【问题描述】:

我正在开发一个 Angular4 + PHP 网站,我使用 Promise 向服务器发送 HTTP 请求,因为我希望我的应用程序根据服务器的响应执行路由。我想访问 then() 中的类变量,但它会抛出 undefined() 错误。

这是我的代码:

status = false;

checkUser(): Promise<any>{
// .....
    return this.http
        .get('http://localhost:8000/api/user', this.options)
        .toPromise()
        .then(this.extractData)
        .catch(this.handleError);
}

private extractData(res: any) {
    data = res.json();
    this.status = data.status; // here it throws error undefined 
    return this.status; 
}

还有其他方法可以实现吗?

【问题讨论】:

  • 再次。将this.extractData 更改为res =&gt; this.extractData(res)。这个问题被一次又一次地问到。
  • @JB Nizet 是的,我同意,它被问了很多次,但是作为一个初学者,打字稿很难跟进其他代码,希望你能理解:)
  • 当然。我自己也犯过这个错误。但谷歌是你的朋友。谷歌搜索你的问题的标题并点击前几个结果会给你答案。
  • @JB Nizet 谢谢!是的,我会遵循它:)

标签: angular http typescript angular-promise


【解决方案1】:

如果您传递函数引用,this 将不再指向本地类实例。

你可以使用bind

.then(this.extractData.bind(this))

或箭头函数

.then((res) => this.extractData(res))

获得所需的行为。

【讨论】:

  • 感谢您的回答:)。它有效
猜你喜欢
  • 1970-01-01
  • 2018-05-13
  • 1970-01-01
  • 2015-12-09
  • 1970-01-01
  • 2015-02-20
  • 1970-01-01
  • 1970-01-01
  • 2012-11-04
相关资源
最近更新 更多