如何在 Promise then() 函数中访问 class 变量?

How to access class variable inside Promise then() function?

我在 Angular4 + PHP 网站上工作,我在其中使用 Promise 向服务器发送 HTTP 请求,因为我希望我的应用程序根据服务器的响应执行路由。我想访问 then() 中的 class 变量,但它抛出 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 将不再指向本地 class 实例。

您可以使用bind

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

或箭头函数

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

以获得所需的行为。