首页 > 解决方案 > 登录后未定义Angular 7令牌

问题描述

尝试获取 Token 值并保持用户登录,直到用户单击注销。如果我尝试将它保存在变量中,它会显示未定义,我可以在其中看到令牌值console.log()

**Auth.service.ts

signIn(email: string, password: string) {
    firebase
      .auth()
      .signInWithEmailAndPassword(email, password)
      .then(response =>
        firebase.auth().onAuthStateChanged(
          (user) => {
            if(user){
              user.getIdToken().then(
                data => this.token = data
              )
            }
          }
        )
      )
      .then(
        response => {
          this.router.navigate(['dashboard']);
        }
      )
      .catch(error => console.log(error));
  }
getToken() {
    firebase.auth().onAuthStateChanged(function(user){
      if(user){
        user.getIdToken().then(
          function(data){
          // console.log(data);
        })
      }
    });
  }

框架:Angular7

标签: angularfirebase-authenticationtoken

解决方案


如果你想打电话then,你需要返回一个Promise。像这样

getToken() {
  return new Promise((resolve, reject) => {
    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        user.getIdToken().then(function(data) {
          resolve(data);
        }).catch(reject);
      } else {
        reject('Error while executing onAuthStateChanged');
      }
    });
  });
}

推荐阅读