我来自 Ionic 1,我从 ionic 2 开始。 当我在 promise 之后立即使用 this.nav.push(nameOftheOterPage) 时出现错误,但是当我在 promise 函数 authHandler 之外使用它时,这个函数 this.nav.push 完全正常工作:
import {Page, NavController} from 'ionic-angular';
import {ItemDetailsPage} from '../item-details/item-details';
@Page({
templateUrl: 'build/pages/login/login.html'
})
export class LoginPage {
static get parameters() {
return [[NavController]];
}
constructor(nav) {
this.nav = nav;
this.firebaseUrl = "https://MYFIREBASE.firebaseio.com";
this.authType = "login";
this.error_username = false;
}
login(form) {
if(form.controls.username.value === null){
this.error_username = true;
}
else{
/* Authenticate User */
var ref = new Firebase(this.firebaseUrl);
ref.authWithPassword({
email : form.controls.username.value,
password : form.controls.password.value
}, this.authHandler);
}
}
authHandler(error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log(authData);
this.nav.push(ItemDetailsPage);
}
}
}
你能帮我吗?
谢谢。
最佳答案
this
的使用在 javascript 对象中有点棘手,尤其是当涉及到回调时。 (我推荐这个 interesting article 关于它)。
要点是,您始终需要跟踪调用函数的对象,因为 this
将绑定(bind)到调用对象。
您的问题的解决方案是 bind你的类的 this
到回调,这样 this
就会是你认为应该的样子。因此,当您调用 authWithPassword
时,请按如下方式进行:
ref.authWithPassword({
email: form.controls.username.value,
password: form.controls.password.value
}, this.authHandler.bind(this));
编辑
正如@Manu Valdés 在评论中建议的那样,如果您想避免使用 bind
,您还有另一种选择,即按以下方式定义 authHandler
:
authHandler = (error, authData) => {
if (error) {
console.log("Login Failed!", error);
} else {
console.log(authData);
this.nav.push(ItemDetailsPage);
}
}
之所以有效,是因为在 arrow functions 中, 它们的 this
被设置为外部执行上下文的那个,不管调用者是谁。
关于javascript - Ionic 2,this.nav.push() 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37399152/