Best way to handle api calls and promises

Hi, i’ve been working on app and im looking a better way to handle this issue, hope its not a noob question:
I have a ResourceService under /providers and there I handle all my api calls, ie:

export class ResourceService {
 headers:Headers = new Headers();
 token: any;
 constructor(
   public http: Http,
   public storage: Storage
 ) {
    this.getToken().then(val => {
      if(!this.token) {
       this.token = val;
      }
   });
 }

public getToken() {
   return this.storage.get("token");
}

interceptor(withToken = false){
   const opts:RequestOptions = new RequestOptions();
   opts.headers = new Headers();
   opts.headers.append('Content-Type', 'application/json');
   if (withToken) {
     opts.headers.append('Authorization', 'Bearer ' + this.token);
   }
 return opts
}

getAddressList(clientId:any) {
  return this.http.get(`${API_ROOT}/clients/${clientId}/address`, this.interceptor(true))
    .map(res => res.json())
    .catch(this.handleError);
}

so my problem is when i call getAddressList if the “this.getToken()” from the constructor hasn’t resolved yet the token is null when i call “this.token” on the interceptor() method.
Im looking for a better way to handle this situation. Any help / direction would be really helpful.

Thanks in advance!

You could provide an init method on your ResourceService which returns a new Promise and resolves when getToken has completed. Then you’d maybe do resourceService.init().then(()=>{ resourceService.getAddressList(); }); or something similar.

This is virtually the same as using angular2-jwt - they do the interceptor bit for you and use storage in the same way (initialized at app module bootstrap).

Your method has the benefit of not taking a dependency you maybe don’t need, but assuming you need to validate the jwt etc it might be easier just to use that.

2 Likes

Hey! thanks for the quick answer. Ill try that approach.