本地存储的角度异步问题

时间:2017-05-16 11:54:45

标签: angular http asynchronous

我刚刚开始使用angular,我正面临着异步操作的一些问题。我正在尝试将类私有值设置为将在http请求中使用的localstorage键值,但http reuqest会在可以从存储中检索密钥之前触发。我正在使用离子原生存储。实施此操作的正确方法是什么?任何帮助将非常感激。 这是我的代码:

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;
    }
  });
}

1 个答案:

答案 0 :(得分:0)

您必须在调用存储回调后发送http请求。这是使用私有方法更新的代码,以使代码更清晰:

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;
            }
        });
    }
}