javascript - 如何在 promise 中返回请求

标签 javascript angular ionic-framework promise ionic2

我正在使用 ionic 2/ Angular 2

我需要执行一个 http 请求,但在此之前我必须使用 Ionic Storage 获取 token 。

我为此创建了一个类ApiRequest

import {Http, Headers, RequestOptions} from '@angular/http';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Storage } from '@ionic/storage';

@Injectable()
export class ApiRequest {

    access_token: string;

    constructor(private http: Http, public storage: Storage) {
        this.storage.get('access_token').then( (value:any) => {
            this.access_token = value;
        });
    }

    get(url) {
        let headers = new Headers({
            // 'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + this.access_token,
            'X-Requested-With': 'XMLHttpRequest'
        });
        let options = new RequestOptions({ headers: headers });

        return this.http.get(url, options)
            .map(res => res.json());

    }

}

然后我就可以这样打电话了

apiRequest.get(this.URL)
        .subscribe(
            data => {
                this.element= data;
            },
            err => {
                console.log(JSON.stringify(err));
            });

我的问题是,this.storage.get异步http.get也是异步,我必须返回 http.get 因为我想在函数外部调用 subscribe

在这种情况下,http.getthis.acess token 收到值之前被调用。

在这种情况下我如何组织我的代码?

最佳答案

这可能有效(我自己没有尝试过):

@Injectable()
export class ApiRequest {

    access_token: string;

    constructor(private http: Http, public storage: Storage) {
        this.storagePromise = this.storage.get('access_token').then( (value:any) => {
            this.access_token = value;
        });
    }

    get(url) {
        let headers = new Headers({
            // 'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + this.access_token,
            'X-Requested-With': 'XMLHttpRequest'
        });
        let options = new RequestOptions({ headers: headers });

        return this.storagePromise.then(
           return token => this.http.get(url, options)
           .map(res => res.json());
        );
    }
}
apiRequest.get(this.URL)
    .then(observable => 
      observable.subscribe(
        data => {
            this.element= data;
        },
        err => {
            console.log(JSON.stringify(err));
        }
      );

关于javascript - 如何在 promise 中返回请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39823569/

相关文章:

javascript - setTimeout(fn,0) 在应用样式之前触发

angular - 单元测试将 Injector 与 Router(和其他服务)一起使用的父类

javascript - 如何在 Angular 4 中使用 SlickGrid(jQuery 遗留库)

Angular2、Ionic2 错误 : has no exported member 'AlertController'

javascript - Javascript 中的树结构

javascript - 从 django 调用 javascript 函数

未创建 Angular 4 代码覆盖文件夹

javascript - 将 Google map 添加到 AngularJS 和 Ionic 应用程序

node.js - 使用 ionic start 时找不到模块 'read'

javascript - iPhone 5s - iOS 9.0.2 - safari - 横向模式时隐藏地址栏