2016-05-17 54 views
1

之外的變量我有這個組件: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之外的變量。有什麼我做錯了嗎?還是有更好的方法來做我想要達到的目標?

回答

2

我會使用箭頭函數來代替。所以,你將能夠(在此組件實例)使用上下文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; 
    } 
    }); 
} 
+0

當我看到的解決方案是多麼簡單是我笑了。這確實起作用。我絕對有更多要了解ES6和JS。謝謝Thierry! –