0

I am trying to send post request so I am retrieving my stored token but I cannot use it in my request function it return [object object]

Code

token: any; //to be used in post request

  constructor(
    private http: HttpClient,
    private env: EnvService,
    private storage: NativeStorage,
  ) {
    this.storage.getItem('token').then((token) => {
      this.token = token; //set token value
      console.log('token', token); // will get the token in console
    }); 
  }

  store(
    name: String,
    description: String,
    phone: String,
    province_id: String,
    kota_id: String,
    address: String,
    logo: String,
    banner: String,
  ) {
    const headers = new HttpHeaders({
      'Accept': 'application/json, text/plain',
      'Content-Type': 'application/json',
      'Authorization': 'Bearer' + " " + this.token //return [object object]
    });
    console.log('header', headers);

    return this.http.post(this.env.STORES_URL,
      { name: name, description: description, phone: phone, province_id: province_id, kota_id: kota_id, address: address, logo: logo, banner: banner }, { headers: headers }
    )
  }

PS: I've commented each part so you can understand better where the problem comes from.

any idea?

Update

I've been playing with this code and if I use

'Authorization': 'Bearer' + " " + JSON.stringify(this.token)

I will get something like:

Authorization: Bearer {"success":{"token":"eyJ0eXAiOiJK....

Still need to go to step forward into token array {"success":{"token":"

Any idea now?**

Update 2

regarding to comment request here is how my token stores in storage (when user loggin)

login(email: String, password: String) {
    return this.http.post(this.env.BASE_URL + '/login',
      { email: email, password: password }
    ).pipe(
      tap(token => {
        console.log(token);
        this.storage.setItem('token', token)
          .then(
            () => {
              console.log('Token Stored');
            },
            error => console.error('Error storing item', error)
          );
        this.token = token;
        this.isLoggedIn = true;
        return token;
      }),
    );
  }
Sangwin Gawande
  • 7,658
  • 8
  • 48
  • 66
mafortis
  • 6,750
  • 23
  • 130
  • 288

3 Answers3

0

I've a similar problem and was because an issue of asyncronity.

I solved like this:

A function to get the token (in a class named global:

getToken() {
    return this.storage.get(this.token_key);
  }

Then a function to create the headers:

async getHeaders() {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + await this.global.getToken()
      })
    };
    return httpOptions;
  }

And when I call the post:

async post(route, postdata){
    this.http.post(route, postData, await this.getHeaders());
}

Hope it helps!

carlonchoboy
  • 35
  • 10
0

Local storage only supports string datatype.

So when storing the token in local storage, convert the object to string using JSON.stringify():

this.storage.setItem('token', JSON.stringify(token));

And when reading the token from local storage, convert back from string using JSON.parse():

this.storage.getItem('token').then((token) => {
      this.token = JSON.parse(token); //set token value
      console.log('token', token); // will get the token in console
}); 
Nikhil
  • 6,493
  • 10
  • 31
  • 68
  • but if i change my token set does it mess with other parts of my app? for instance i'm using this token to validate user login for page guards like: `'Authorization': this.token["token_type"] + " " + this.token["access_token"]` and if i change that part should later i change all other functions as well? – mafortis Aug 21 '19 at 04:30
  • what if i just use `'Authorization': 'Bearer' + " " + JSON.stringify(this.token['token'])` would it work you think? – mafortis Aug 21 '19 at 04:32
  • Can you update your question with output of `console.log(token)` when setting the token in local storage? Right now you are not storing the token value, you are just storing `[object Object]` string. – Nikhil Aug 21 '19 at 04:33
  • @mafortis - You can see that the response object is {`'success': {'token': ...}}`. So, when storing the token store it as, `this.storage.setItem('token', token.success.token);` Let me know if this works. – Nikhil Aug 21 '19 at 04:57
  • OK i've tried `JSON.stringify(token.success.token)` it didn't even create the app it says there is no such `success` and then i tried `JSON.stringify(token)` https://ibb.co/MMMsr2D and `this.storage.getItem('token').then((token) => { this.token = JSON.parse(token);` then it return `[object object]` so basically i don't think there is any issue with the way my token is stored but the way I try to get it. – mafortis Aug 21 '19 at 05:21
  • maybe we need to add some sort of `async` to my function? so it gets the token first then execute `store` function? – mafortis Aug 21 '19 at 05:22
  • I think this is an issue with storing the token itself. After user logs in, check the local storage in the browser and see what you have in there. That should help clarify things. – Nikhil Aug 21 '19 at 05:33
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/198216/discussion-between-nikhil-and-mafortis). – Nikhil Aug 21 '19 at 05:42
0

SOLVED

Based on Update 1 in my question now i can get my token like this code and my problem is solved.

'Authorization': 'Bearer' + " " + this.token.success.token

There was no need of JSON.stringify() or JSON.parse()

Thanks for all helps.

mafortis
  • 6,750
  • 23
  • 130
  • 288