AngularFire2 4 Token 仅由第二次调用

AngularFire2 4 Token only by the second call

我有一个 Angular4 项目并使用 AngularFire2 4 实现 Auth!

在我的登录表单中,我有一个调用登录功能的按钮:

login() {
this.afAuth.auth.signInWithEmailAndPassword(this.model.email, 
this.model.password).then(
    (success) => {
this.afAuth.auth.currentUser.getIdToken().then(function (token) {
      //console.log(token);
localStorage.setItem("JwtToken", token);
})
    }).catch(
    (err) => {
        //this.error = err;
    });
       this.dataService.gettestToken();
}




//this is the Function in the Dataservice 
public gettestToken(){
console.log(localStorage.getItem('JwtToken'));
}

登录后,我将 IdToken 写入 localStorage 以备后用 访问 ASP.NET WebAPI 数据....

我现在的问题是: 我可以在 localStorage 中写入正确的 IDToken 但是当我在数据服务中调用函数 getTestToken 时 为了使用 console.log 进行测试,我变得没有令牌返回...只有 null。

但疯狂的事情是当我点击第二个登录按钮时 那我就变回Token了!

我必须始终点击登录按钮 2 次才能成为我的令牌...

但是当我锁定本地存储下的开发者工具时,令牌是 通过第一次点击登录按钮编写....

有没有人知道我的问题在哪里或者这是一些错误?

您正在两个异步函数之外调用 this.dataService.gettestToken();

gettestToken() return 为空,因为 signInWithEmailAndPassword 没有 return 承诺,getIdToken() 也没有。

您需要像这样将 this.dataService.gettestToken()getIdToken() 移动到 .then()

login(__this = this) {
  this.afAuth.auth.signInWithEmailAndPassword(this.model.email, 
    this.model.password).then((success) => {
      this.afAuth.auth.currentUser.getIdToken().then(function (token) {
        //console.log(token);
        localStorage.setItem("JwtToken", token);
        // MOVE FUNCTION HERE ******************
        __this.dataService.gettestToken(); // <--------
      })
    }).catch((err) => {
    //this.error = err;
    });
}




//this is the Function in the Dataservice 
public gettestToken(){
  console.log(localStorage.getItem('JwtToken'));
}

编辑: 请注意,我必须向 login() 函数添加一个参数:__this = this。这是因为当 this 在 promise 中时 return this 不是指 class.