How to wait for reading data from localstorage in constructor?


#1

Hello!

I want to read the token from localstorage in the constructor to build the header for http calls. My problem is that because reading from storage takes a while, my function which uses the token will be executed before the constructor.
How can I resolve this?
I tried with promise with no luck, my latest code is the following:

contentHeader: Headers;

    constructor(public http: Http, public storage: Storage) {
        console.log('Hello Announcements Provider');
        this.getLocalStorageData()
            .then(data =>{
                  //ok
            })
    }

    getLocalStorageData(){
        return new Promise(resolve => {
            this.storage.get('token').then((value) => {
                this.contentHeader = new Headers({
                    "Content-Type": "application/json",
                    "Authorization": "Bearer " + value
                });
                resolve(value);
            });
        })
    }

Thank you for any kind of help.


#2

You don’t show the “function which uses the token”, so I’m just going to have to make one up, but there’s no need to instantiate another promise. Just use the one that storage is giving you.

private _headers: Promise<Headers>;

constructor(private _http: Http, private _storage: Storage) {
  this._headers = this._storage.get('token').then((token) => {
    return new Headers({
      "Content-Type": "application/json",
      "Authorization": "Bearer " + token,
  });
}

fetchThingies(): Observable<Thingy[]> {
  return Observable.fromPromise(this._headers).mergeMap((headers) => {
    return this._http.get('/api/thingies', {headers: headers}).map(rsp => rsp.json() as Thingy[]);
  });
}

#3

Hm. Thank you very much. Now it’s ok.
Thank you again :wink: