Rub*_*bia 3 promise es6-promise ionic2 angular
我有一个返回承诺的方法,如:
checkLogin(credentials) {
return new Promise((resolve, reject) => {
this.http.post(url, credentials)
.map(res => res.json())
.subscribe(
data => {
resolve(data);
},
err => {
reject(err);
}
);
});
}
Run Code Online (Sandbox Code Playgroud)
我把这个方法称为另一个:
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)
});
}
Run Code Online (Sandbox Code Playgroud)
这是错误发生的地方,它被称为"TypeError:this.doAlert不是函数":
但是doAlert与其他文件在同一个文件中,并且在其他地方工作正常(不是承诺调用)
doAlert(text) {
let alert = Alert.create({
title: 'Alert;,
subTitle: text,
buttons: ['Ok']
});
this.nav.present(alert);
}
Run Code Online (Sandbox Code Playgroud)
是不是可以这样做?
Gün*_*uer 13
请改用fat-arrow函数
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)
});
}
Run Code Online (Sandbox Code Playgroud)
保持范围
另请参阅
- https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html
- https://github.com/Microsoft/TypeScript/wiki/'this'- in-TypeScript
- 含义是什么TypeScript中的"=>"?(胖箭)
使用箭头函数
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)
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3204 次 |
| 最近记录: |