Search code examples
typescripthttpclientangular8

How to Store data from httpClient Post response?


I am trying to store a token on session storage after getting a response but when I compile this code I get error Property 'access_token' does not exist on type 'Object'. This error is showing before sending a request and i want to execute sesssionstorage when i get a response not before sending a request.

 this.http.post(url,null,
   {
     headers : new HttpHeaders({
      'Content-Type': 'application/x-www-form-urlencoded',
     'Authorization' :'Basic '+ btoa('username:password')
     })
   }
   ).subscribe(
    data => { // json data

      console.log('Success: ', data);
      sessionStorage.setItem("Token ",data.access_token)
  },
  error => {
      console.log('Error: ', error);
  }
   )


  }

Solution

  • what is your response data type? you could use any type and write it like this.but the good practice is to write an interface with response data.

      {
        headers : new HttpHeaders({
         'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization' :'Basic '+ btoa('username:password')
        })
      }
      ).subscribe(
       (data: any) => { // json data
    
         console.log('Success: ', data);
         sessionStorage.setItem("Token ",data.access_token)
       },
       error => {
         console.log('Error: ', error);
       }
      )
     }