如何避免可观察的角度延迟或确保仅当可观察的状态准备好时才调用我的函数

时间:2018-12-11 22:00:35

标签: javascript angular firebase observable angularfire

我有一个登录功能,该功能调用Firebase SDK方法以通过电子邮件进行身份验证。此Firebase方法返回UserCredential的非空Promise,因此在Firebase文档中说。因此,我使用.then()等待用户登录,通过身份验证,然后console.log他的信息并重定向到首页。不幸的是,它不起作用。我从控制台中的console.log(value.email);中获得了未定义,从

中获得了not working
if (this.userDetails) {
console.log("hello im user" + " " + email);
} else {
console.log("not working");
}

errorTypeError: Cannot read property 'router' of undefined来自:

.catch(function(error) {
      // Handle Errors here.
      var errorCode = error.code;
      var errorMessage = error.message;
      console.log("error" + error);
    });

然后一两秒钟后,它终于开始工作,并从

打印出hello im user lajmis@mail.com
constructor(private _firebaseAuth: AngularFireAuth, private router: Router) {
    this.user = _firebaseAuth.authState;
    this.loggedIn = !!sessionStorage.getItem('user');

    this.user.subscribe(
        (user) => {
          if (user && user.uid) {
            this.userDetails = user;
            var email = this.userDetails.email;
            console.log("hello im user" + " " + email);
            this.setCurrentUser(email);
            this.loggedIn = true;
            console.log(this.userDetails);

          } else {
            this.userDetails = null;
          }
        }
      );
  }

this.userDetails

为什么会这样?这是完整的代码:

export class AuthService {
  private user: Observable<firebase.User>;
  private userDetails: firebase.User = null;
  public loggedIn = false;

  constructor(private _firebaseAuth: AngularFireAuth, private router: Router) {
    this.user = _firebaseAuth.authState;
    this.loggedIn = !!sessionStorage.getItem('user');

    this.user.subscribe(
        (user) => {
          if (user && user.uid) {
            this.userDetails = user;
            var email = this.userDetails.email;
            console.log("hello im user" + " " + email);
            this.setCurrentUser(email);
            this.loggedIn = true;
            console.log(this.userDetails);

          } else {
            this.userDetails = null;
          }
        }
      );
  }

  // Set current user in your session after a successful login
    setCurrentUser(email: string): void {
        sessionStorage.setItem('user', email);
        this.loggedIn = true;
    }

    // Get currently logged in user from session
    getCurrentUser(): string | any {
        return sessionStorage.getItem('user') || undefined;
    }

    isLoggedIn() {
    return this.loggedIn;
    }

  logUserIn(email, pass) {
    firebase.auth().signInWithEmailAndPassword(email, pass).then(function(value) {

        console.log(value.email);
        this.router.navigate(['']);

    }).catch(function(error) {
      // Handle Errors here.
      var errorCode = error.code;
      var errorMessage = error.message;
      console.log("error" + error);
    });
if (this.userDetails) {
console.log("hello im user" + " " + email);
} else {
console.log("not working");
}
}

1 个答案:

答案 0 :(得分:1)

logUserIn是无阻塞的-因此工作流程将是

  • 致电constructor
  • 致电this.user.subscribe
  • 致电logUserIn
  • 致电firebase.auth().signInWithEmailAndPassword
  • 致电if (this.userDetails)
  • 接收来自firebase.auth().signInWithEmailAndPassword的回复
  • 致电.then(function(value) {
  • 致电this.router.navigate(['']);
  • 接收来自this.user.subscribe的回复

因此console.log将输出not working,几秒钟后this.user.subscribe将收到user对象。

router无法访问,因为您没有使用arrow function。使用arrow function来维持对this的访问权限。

也许尝试以下工作流程;

constructor(private _firebaseAuth: AngularFireAuth, private router: Router) {
  this.user = _firebaseAuth.authState;
  this.loggedIn = !!sessionStorage.getItem('user');

  this.user
    .subscribe(user => {
      console.log('constructor user: ' + user);
      this.updateUser(user);
    });
}

updateUser(user) {
  if (user && user.id) {
    this.userDetails = user;
    var email = this.userDetails.email;
    console.log("hello im user" + " " + email);
    this.setCurrentUser(email);
    this.loggedIn = true;
    console.log(this.userDetails);
  } else {
    this.userDetails = null;
  }
}

logUserIn(email, pass) {
  firebase.auth().signInWithEmailAndPassword(email, pass)
    .then(user => {
      console.log('logUserIn: ' + user);

      this.updateUser(user);

      this.router.navigate(['']);
    })
    .catch(error => {
      // Handle Errors here.
      var errorCode = error.code;
      var errorMessage = error.message;
      console.log("error" + error);
    });
}

这样logUserInconstructor都可以在从Firebase接收到用户对象时更新userDetails

这还将避​​免您在设置this.userDetails之前进行重定向。