简体   繁体   中英

Angular async problems with local storage

I am just starting out with angular and i am facing some issues with async operations. I am trying to set a class private value to a localstorage key value that will be used in a http request, but the http reuqest fires off before the key can be retrieved from the storage. I am using ionic native storage. What is the proper way to implement this operation? Any help would be much appreciated. Here is my code:

export class EventService {
 constructor(private _http: Http, private _storage: Storage) {
}

private url = 'http://website.com';
private token : string;

getEventsAction() {
  this._storage.ready().then(() => {
    this._storage.get('auth_token').then((val) => {
      this.token = val;
    });
});

let params = {
  "query": {
    "search_term": "", "page": 1
  }
};
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Auth-Token', this.token);

let options = new RequestOptions({headers: headers});

return this._http.post(this.url + '/api/events/list', params, options)
  .map((response: Response) => {
    let events = response.json();
    if (events) {
      return events;
    }
  });
}

You have to send the http request after the storage callback has been called. This is your code updated with private methods in order to make to code cleaner :

export class EventService {
    constructor(private _http: Http, private _storage: Storage) { }

    private url = 'http://website.com';
    private token : string;

    getEventsAction() {
        this.retrieveToken().catch(() => {
            // You can log something here, the 'then' callback will be always executed anyway
        }).then(() => { 
            this.sendHttpRequest();
        });
    }

    private retrieveToken(): Promise<any> {
        return this._storage.ready().then(() => {
            return this._storage.get('auth_token').then((val) => {
                this.token = val;
            }).catch(() => {
                // Set default token if storage.get() raised an exception
                this.token = 'defaultToken';
            });
        });
    }

    private sendHttpRequest() {
        let params = {
            "query": {
                "search_term": "", "page": 1
            }
        };
        let headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');
        headers.append('Access-Control-Allow-Origin', '*');
        headers.append('Auth-Token', this.token);

        let options = new RequestOptions({headers: headers});

        return this._http.post(this.url + '/api/events/list', params, options)
        .map((response: Response) => {
            let events = response.json();
            if (events) {
                return events;
            }
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM