Angularfire2电子邮件认证引用承诺
问题描述:
之外的变量我有这个组件:Angularfire2电子邮件认证引用承诺
export class LoginComponent {
login_error = "";
constructor(public af: AngularFire) {
this.af.auth.subscribe(auth => console.log(auth));
}
login(credentials) {
this.af.auth.login({ email: credentials.email, password: credentials.password})
.catch(function (error) {
switch (error.code) {
case "INVALID_USER":
console.log("Invalid email");
this.login_error = "Email is invalid"; //<----- broken
break;
case "INVALID_PASSWORD":
console.log("Invalid password");
this.login_error = "Password is invalid"; //<----- broken
break;
default:
break;
}
});
}
logout(){
this.af.auth.logout();
}
}
我希望能够设置login_error变量(.catch内),这是在使用模板来通知用户他们的电子邮件或密码不正确,但我无法引用Promise之外的变量。有什么我做错了吗?还是有更好的方法来做我想要达到的目标?
答
我会使用箭头函数来代替。所以,你将能够(在此组件实例)使用上下文this
:
login(credentials) {
this.af.auth.login({ email: credentials.email, password: credentials.password})
.catch((error) => { // <-------
switch (error.code) {
case "INVALID_USER":
console.log("Invalid email");
this.login_error = "Email is invalid";
break;
case "INVALID_PASSWORD":
console.log("Invalid password");
this.login_error = "Password is invalid";
break;
default:
break;
}
});
}
当我看到的解决方案是多么简单是我笑了。这确实起作用。我绝对有更多要了解ES6和JS。谢谢Thierry! –