I create a simple login form on Angular (v8). On return response, I save it in localStorage like this
this.loginCtrl.login(form.value).subscribe(
response => {
console.log(response["token"]); //IS CORRECT
if (response["token"] != null) {
localStorage.setItem("token", response["token"]);
}
})
Then I want to get the token and send it to other services.
const httpOptions = {
headers: new HttpHeaders({
Authorization: "Token " + localStorage.getItem("token")
})
};
getGroupsByEntityAndUser(id: string, user: String) {
return this.http.get(
"URL" +
id +
"/username/" +
user,
httpOptions
);
}
The problem appears when I load the home page. The console returns that the token is null so the response is null. When I refresh the page with F5 I get the token and getGroupsByEntityAndUser function works properly. It´s a bit strange.
So the question is: Why when I load the first time localStorage is null but when I refresh the page is filled? It is necessary to be filled without refresh.