Search code examples
javascriptangularpromiseangular2-services

Fetching value via promise Angular in custom service


I have this code:

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Storage } from '@ionic/storage';
import { AppSettings } from './shared';

@Injectable()
export class HttpClient {

    constructor(private http: Http, private storage: Storage) { }

    createAuthorizationHeader(headers: Headers) {
        var token: string = '';
        this.storage.get(AppSettings.StorageKeys.Token).then(value => {
            token = value;
        });
        headers.append('Authorization', 'Bearer ' + token);
    }

    get(url) {
        let headers = new Headers();
        this.createAuthorizationHeader(headers);
        return this.http.get(url, {
            headers: headers
        });
    }

    post(url, data) {
        let headers = new Headers();
        this.createAuthorizationHeader(headers);
        return this.http.post(url, data, {
            headers: headers
        });
    }
}

The problem here is:

this.storage.get(AppSettings.StorageKeys.Token).then(value => {
            token = value;
        });

This is promise. So how do I change the createAuthorizationHeader function such the headers are appended properly?

This is Ionic2 code but mostly the issue is related to working of promises.


Solution

  • createAuthorizationHeader isn't returning a promise, and you should create Authorization token from promise function success. Also get of your service should return promise, for the same you could use .toPromise() to return promise inspite of Observable. But as you don't won't to loose observable sauce, you should consider converting createAuthorizationHeader method to return Observable. Observable.fromPromise will rescue us in this situation to convert Promise to Observable.

    Code

    createAuthorizationHeader(headers: Headers) {
        var token: string = '';
        let headers = new Headers();
        return Observable.fromPromise(this.storage.get(AppSettings.StorageKeys.Token)
          .then(value => {
            token = value;
            headers.append('Authorization', 'Bearer ' + token);
            return headers;
          }
        );
    }
    
    get(url) {
        return this.createAuthorizationHeader()
         .switchMap((headers)=> this.http.get(url, {
            headers: headers
          });
        })
    }