[英]Angular 2 `this` reference in promise
我的服务具有以下代码:
....
isAuthenticated(){
var tt = this;
if(tt.current_user){
return Promise.resolve(tt.current_user,false);
}else{
return new Promise(resolve => {
this.http.get(this.api.urlBase+this.api.apiBase+'/Individuals/me',
{withCredentials: true})
.map(res=>res.json())
.subscribe((data) => {
tt.current_user = data;
resolve(data,false);
},(err)=>{
reject(err,true);
});
})
}
}
....
在页面类中,我尝试以以下方式访问它:
constructor(){
...
let tt = this;
individual.isAuthenticated().then(this.handleLogin);
...
}
...
handleLogin(d,err){
console.log("This: ",this);
console.log("This: ",tt);
this.nav.present(this.loading);
}
但在handleLogin
, this.nav
抛出了一个错误this
是不明确的,并且控制台日志显示this
空白和tt
为未定义。 我如何从该函数中引用this
?
您需要包装方法调用或在其上调用bind
方法
constructor() {
...
let tt = this;
individual.isAuthenticated().then((data) => { // <----
this.handleLogin(data)
});
...
}
...
handleLogin(d,err){
console.log("This: ",this);
console.log("This: ",tt);
this.nav.present(this.loading);
}
要么
constructor() {
...
let tt = this;
individual.isAuthenticated().then(this.handleLogin.bind(this));
...
}
...
handleLogin(d,err){
console.log("This: ",this);
console.log("This: ",tt);
this.nav.present(this.loading);
}
在TypeScript中使用bind
方法有一个缺点,因为您失去了原始函数签名的类型安全性。 有关更多详细信息,请参见此链接:
将handleLogin
定义为属性而不是方法
//handleLogin(d,err){
handleLogin = (d,err) => {
console.log("This: ",this);
console.log("This: ",tt);
this.nav.present(this.loading);
}
这将使this
工作按预期进行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.