2016-12-20 137 views
1

我怎樣才能改變這種代碼(承諾):Angular2無極異步/等待

registerUser(formData) { 
    firebase.auth().createUserWithEmailAndPassword(formData.email,formData.passwords.password) 
      .then((user) => { 
       firebase.database().ref(`/users/${user.uid}`).set({ 
        id: user.uid, 
        email: formData.email 
       }) 
       this.routing.navigate(['/login']); 
      }).catch((error) => { 
       console.log(error); 
      }) 
} 

進入這個(異步/等待):

async registerUser(formData){ 
    try{ 
     await firebase.auth().createUserWithEmailAndPassword(formData.email,formData.passwords.password); 
     firebase.database().ref(`/users/${user.uid}`) 
      .set({id: user.uid,email: formData.email}); 
     this.routing.navigate(['/login']); 
     return true; 
    }catch(error){ 
     return false; 
    } 
} 

我怎樣才能得到user.uid(這是註冊用戶uid)?在承諾中很容易,因爲我只需要傳遞參數(用戶)即可。 謝謝,求助:)

回答

3

我怎樣才能得到user.uid ...

userawait表達式返回,所以在它前面加上let user =(或const user =):

async registerUser(formData){ 
    try{ 
     const user = await firebase.auth().createUserWithEmailAndPassword(formData.email,formData.passwords.password); 
    // ^^^^^^^^^^^^^ 
     firebase.database().ref(`/users/${user.uid}`) 
      .set({id: user.uid,email: formData.email}); 
     this.routing.navigate(['/login']); 
     return true; 
    }catch(error){ 
     return false; 
    } 
} 
+0

非常感謝你! :) – qwerty1234567