【问题标题】:How return a request inside a promise如何在承诺中返回请求
【发布时间】:2016-10-03 01:51:12
【问题描述】:

我正在使用 ionic 2 / angular 2

我需要做一个 http 请求,但在我必须使用 Ionic Storage 获取令牌之前。

我为此创建了一个类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 令牌收到值之前被调用。

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

【问题讨论】:

标签: javascript angular ionic-framework promise ionic2


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2017-05-15
    • 2017-02-22
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    • 2014-10-31
    相关资源
    最近更新 更多