如何在承诺中返回请求

How return a request inside a promise

本文关键字:返回 请求 承诺      更新时间:2023-09-26

我正在使用离子2/角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也是非异步

在这种情况下,在this.acess令牌接收到值之前调用http.get

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

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

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