Search code examples
typescriptangular8session-storage

How to Get value from session on Oninit in angular8?


I am Storing access token on session storage during the time of login and accessing it on other components oninit() method but getting null value. checked on the console it stores token on session .

Here is set session storage on post httpclient request

.subscribe(
    (data: any) => { // json data

      console.log('Success: ', data);
      sessionStorage.setItem("Token ",data.access_token)
        this._router.navigate( ['dashboard'] );

  }, 

and here i am accessing this token on other component

ngOnInit() {
    let url:string = '.......';
     const token  = sessionStorage.getItem("Token");
     console.log(token);


    this.http.get(url,
    {
      headers : new HttpHeaders({
       'Content-Type': 'application/x-www-form-urlencoded',
      'Authorization' :'Bearer '+ token
      })
    }
    ).subscribe(
      (data: any)=> { // json data

       console.log('Success: ', data.data);
      this.leads = data.data;


   },
   error => {
       console.log('Error: ', error);
   }
    )
  }

} 

Solution

  • You have an extra space at registering the Token.

          sessionStorage.setItem("Token ",data.access_token)
    

    Remove the extra space after token and it should work.