簡體   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