Reputation: 11
I have a Angular4 Project and implement Auth with AngularFire2 4 !
in my Login Form i have a Button who calls the login Function:
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'));
}
after Login I write the IdToken in the localStorage to use them later to access to ASP.NET WebAPI Data....
my Problem now is: I can write the correct IDToken in the localStorage but when i call the Function getTestToken in the Dataservice for testing with console.log i become no Token Back... only null.
but the crazy Thing is when i click a second one to the Login Button then i become the Token back!
i must click always 2 Times the Login Button to become my Token back...
but when i lock in the Developer Tools under Local Storage is the Token written by the first click of the Login Button....
has someone an Idea where is my Problem or is this some Bug?
Upvotes: 0
Views: 416
Reputation: 867
You are calling this.dataService.gettestToken();
outside of two async functions.
gettestToken()
is returning null because signInWithEmailAndPassword
hasn't returned a promise and neither has getIdToken()
.
You need to move this.dataService.gettestToken()
into then .then()
from getIdToken()
like this:
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'));
}
EDIT:
Notice I had to add a parameter to the login()
function: __this = this
. This is because when this
is inside of the promise return this
is not referring to the class.
Upvotes: 2