繁体   English   中英

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

[英]How to avoid observable delay in angular or make sure my function gets called only when observable is ready

我有一个登录功能,该功能调用Firebase SDK方法以通过电子邮件进行身份验证。 此Firebase方法返回UserCredential非空Promise,因此在Firebase文档中说。 因此,我使用.then()等待用户登录,通过身份验证,然后console.log他的信息并重定向到首页。 不幸的是,它不起作用。 我从console.log(value.email);得到未定义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从以下位置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打印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");
}
}

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.lognot 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之前this.userDetails重定向。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM