数据延迟到达不同组件的角度

时间:2018-08-29 11:41:21

标签: javascript angular firebase firebase-realtime-database firebase-authentication

我使用angular 6和firebase作为后端。 我从用户检索数据并将其存储在localstorage中,登录页面重定向到用户的个人资料。由于数据迟到,因此字段中未显示任何内容。交易是在页面加载之后进行的。我无法通过连接期间而不是在个人资料页面上对数据的调用来作出承诺。

SigninComponent.ts

onSubmit() {
    const email = this.siginForm.get('email').value;
    const password = this.siginForm.get('password').value;

    this.authService.signInUser(email, password).then(
      () => {
        firebase.auth().onAuthStateChanged((user) => {
          if (user) {
             var ref = firebase.database().ref('users/' + user.uid).on('value', 
                 (data) =>
                localStorage.setItem("userInfo", JSON.stringify(data.val()))

            );
          }
        });      
        this.router.navigate(['Acceuille']);
      },
      (error) => {
        this.errorMessage = error;
      }
    );
}

1 个答案:

答案 0 :(得分:0)

您应将这一行放在“ this.router.navigate(['Acceuille']);;”在“ if”块中检查用户后,在firebase.auth()。onAuthStateChanged()方法内部;

this.authService.signInUser(email, password).then(
  () => {
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
         var ref = firebase.database().ref('users/' + user.uid).on('value', 
             (data) =>
            localStorage.setItem("userInfo", JSON.stringify(data.val()));
            this.router.navigate(['Acceuille']); // navigation should be here
        );
      }
    });      
          },
  (error) => {
    this.errorMessage = error;
  }
);

因为onAuthStateChange等待观察者等待,直到getRedirectResult解析。 See how to get the currently signed in user in this doc