本地存储的 Angular 异步问题

标签 angular http asynchronous

我刚开始使用 Angular,我正面临一些异步操作的问题。我正在尝试将类私有(private)值设置为将在 http 请求中使用的本地存储键值,但在可以从存储中检索键之前,http reuqest 会触发。我正在使用 ionic native 存储。实现此操作的正确方法是什么?任何帮助将非常感激。 这是我的代码:

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

最佳答案

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

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

关于本地存储的 Angular 异步问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44000763/

相关文章:

angular - 仅当响应成功时如何使表单路由(Angular 4)

asynchronous - 为什么 Async.StartChild 返回 `Async<Async<' T>>`?

asp.net - Task.Run 之后 HttpContext.Current 为 null

http - 如何在 Dart 中对 URL 进行编码?

javascript - 从异步调用返回一个数组,然后对数组的每个元素进行额外的异步调用

node.js - Angular 7 TypeError : Cannot read property 'hasOwnProperty' of undefined

angular - 如何编写 Angular2 npm 模块 - Angular2 RC 6

javascript - BrowserAuthError : interaction_in_progress - Unable to fix, 无论找到什么解决方案

javascript - 在每个文档上单击我想在 debounceTime() 函数中传递不同的值

php - localhost 目前无法处理此请求。 Laravel 的 HTTP 错误 500