Sur*_*mad 5 http typescript angular-promise angular
我正在一个 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;
}
Run Code Online (Sandbox Code Playgroud)
有没有其他方法可以实现这一点?
Gün*_*uer 12
如果传递函数引用,this则不再指向本地类实例。
您可以使用 bind
.then(this.extractData.bind(this))
Run Code Online (Sandbox Code Playgroud)
或箭头函数
.then((res) => this.extractData(res))
Run Code Online (Sandbox Code Playgroud)
以获得所需的行为。