I have a method which returns a promise like:
checkLogin(credentials) {
return new Promise((resolve, reject) => {
this.http.post(url, credentials)
.map(res => res.json())
.subscribe(
data => {
resolve(data);
},
err => {
reject(err);
}
);
});
}
I call this method inside another:
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)
});
}
Here is where the error happens, it is said "TypeError: this.doAlert is not a function":
But the doAlert is in the same file than the others, and it works fine from other places (not promises calls)
doAlert(text) {
let alert = Alert.create({
title: 'Alert;,
subTitle: text,
buttons: ['Ok']
});
this.nav.present(alert);
}
Is it not possible to do this?
Use fat-arrow functions instead
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)
});
}
to keep the scope
See also
- 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With