Search code examples
angularionic2angular2-jwt

Set dynamic headers in Ionic 2 with angular2-jwt


When users login to my app they have to say to which club they belong. Once they select the club I save that in storage and attach it to header. Here is the code I currently have:

let storage: Storage = new Storage();

export function getSubdomain(){
  return new Promise((resolve, reject) => {
    storage.get('club').then(club => {
      console.log(club);

      resolve(club)
    })
  });
}

export function getAuthHttp(http: Http, options: RequestOptions) {
  return new AuthHttp(new AuthConfig({
    noJwtError: true,
    globalHeaders: [{'Content-Type': 'application/json'}, {'x-academy': getSubdomain()}],
    tokenGetter: (() => storage.get('id_token'))
 }), http, options);
}

Problem is that getSubdomain() function doesn't return the name before header is called. I understand that problem is async. It works perfectly fine if I put return "clubname". How do I solve this?


Solution

  • I wansn't able to work the problem out using Storage so I had to use localstorage.getItem('club') since it's sync function and it looked like this:

    export function getAuthHttp(http: Http, options: RequestOptions) {
      return getSubDomain().then(subDomain => 
        new AuthHttp(new AuthConfig({
        noJwtError: true,
        globalHeaders: [{'Content-Type': 'application/json'}, {'x-academy': localstorage.getItem('club')}],
        tokenGetter: (() => storage.get('id_token'))
      }), http, options));
    }