1

I made jwt authorization and I stored that token into session storage , but when i try to get that token into string and log it i get null , this is the function

login(user : User): void
  {
    this.header= new Headers({"content-Type": "application/json"});
    this.osobaService.create(user,this.tokenUrl,this.header).then(p=> {sessionStorage.setItem("Token",p._body.slice(1,-1))});
    this.tokenString = sessionStorage.getItem("Token");
    console.log(this.tokenString);
  }

It should be simple getItem method but I'm getting null .

  • what type of Object is p? try to log this value here: .then(p=> {console.log("Token:",p._body.slice(1,-1));sessionStorage.setItem("Token",p._body.slice(1,-1))}) Maybe this gives you a hint where to search for the error. – Joniras Dec 06 '17 at 09:30
  • is your `osobaService ` callback or got any resolve function? – Rach Chen Dec 06 '17 at 09:37

1 Answers1

3

The 'this.osobaService.create' is a async function. You are trying to log a value, before writing it. If you change your code like this, this should log a correct value.

login(user : User): void
  {
    this.header= new Headers({"content-Type": "application/json"});
    this.osobaService.create(user,this.tokenUrl,this.header)
        .then(p=> {
             sessionStorage.setItem("Token",p._body.slice(1,-1))
             this.tokenString = sessionStorage.getItem("Token");
             console.log(this.tokenString);
        });
  }
Alexander_F
  • 2,831
  • 3
  • 28
  • 61