Get Token From Ionic Storage For Header in Ionic Native HTTP

Good day! I am trying to use Ionic Native HTTP for requesting API data to Server. I also want to get Authorization Token that stored in Ionic Storage. Below are my code

import { HelperService } from './helper.service';
import { HTTP, HTTPResponse } from '@ionic-native/http/ngx';
import { Storage } from '@ionic/storage';

  constructor(private helper: HelperService, private nativeHttp: HTTP, private storage: Storage) {}

  deleteShipping(shipping): Promise<HTTPResponse>{
    this.shipping.forEach(result => {
      if(shipping.id === result.id){
        this.shipping = [];
      }
    })

    let headers: {};

    this.storage.get(this.helper.TOKEN_KEY).then(token => {
      headers = {
        'Authorization': 'Bearer '+ token
      };
    })
    
    return this.nativeHttp.delete(this.helper.API_URL+'/user/shipping/'+shipping.id, {}, headers);
  }

When im trying to delete, it fails. because the headers is empty. the server blocked the request because there is no token from the request. Any help would be appreciated. Thank you.

storage.get returns a Promise, so is asynchron. The last return Line is executed before the headers are initalized, that’s why they are empty

2 Likes

You need a http interceptor to deal with adding the token to all / select http calls, else you will have to repeat adding the token for all http calls you need to make :frowning: violating DRY.

There are numerous tutes online about auth service providers and http interceptors when it come to authentication and authorization in ionic / angular apps that help do all the heavy lifting.

Separation of concerns is very important for varying reasons like maintenance and future scaling of an app. Have an auth service to deal with user authentication and authorization making it easier for other modules to get / ask for user related info from it. This module will deal with things like fetching the token and providing it to the rest of the app when needed.

This will also involve using observables and observers.

If you follow this pattern you’ll cure this problem and many other issues that are right now unforeseen.

2 Likes

thanks for the infomation, i’ve search the interceptor, but all the tutor only shows the angular http interceptor, not native. can you show some link to me for native http interceptor?

hey! thanks… ill do the request inside the promise :smile:

Ionic is framework agnostic, so if you are using angular then those tutes are very much applicable.

I would be very surprised if that was the takeaway @EinfachHans intended from that comment. A major reason that futures such as Promises and Observables became fashionable is to eliminate the need for nested callback snarls.

Make chains, not onions.

1 Like