我有一个返回 promise 的方法,例如:
checkLogin(credentials) {
return new Promise((resolve, reject) => {
this.http.post(url, credentials)
.map(res => res.json())
.subscribe(
data => {
resolve(data);
},
err => {
reject(err);
}
);
});
}
我在另一个里面调用这个方法:
login(credentials) {
this.checkLogin(credentials)
.then(function(result) {
console.log("ok: ",result);
this.doAlert("ok");
})
.catch(function(err) {
console.log("error: ",err.message);
this.doAlert(err.message)
});
}
这里是错误发生的地方,据说“TypeError: this.doAlert is not a function”:
但是 doAlert 与其他文件在同一个文件中,并且它在其他地方工作正常(不是 promises 调用)
doAlert(text) {
let alert = Alert.create({
title: 'Alert;,
subTitle: text,
buttons: ['Ok']
});
this.nav.present(alert);
}
难道这不可能吗?
最佳答案
改用粗箭头函数
login(credentials) {
this.checkLogin(credentials)
.then((result) => {
console.log("ok: ",result);
this.doAlert("ok");
})
.catch((err) => {
console.log("error: ",err.message);
this.doAlert(err.message)
});
}
保持范围
另见
- https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html
- https://github.com/Microsoft/TypeScript/wiki/ 'this'-in-TypeScript
- What's the meaning of "=>" in TypeScript? (Fat Arrow)
关于promise - 无法在 catch 或 Promise 调用中调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35627129/