有可能以某种方式同步调用异步离子存储吗?

时间:2016-12-13 11:26:42

标签: angular typescript ionic-framework ionic2 angular2-http

我正在尝试创建一个在export class APIRequest extends Http { private storage : Storage; constructor (backend: XHRBackend, options: RequestOptions) { super(backend, options); this.storage = new Storage; } request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> { if (typeof url === 'string') { url = AppConfig.API_SERVER + url } else { url.url = AppConfig.API_SERVER + url.url } this.storage.get('authToken').then(token => { if (typeof url === 'string') { if (!options) { options = {headers: new Headers()}; } options.headers.set('Authorization', `Bearer ${token}`); } else { url.headers.set('Authorization', `Bearer ${token}`); } // Here I need to return }, err => { // throw some error }) return super.request(url, options).catch(this.catchAuthError(this)); } } 类之上使用API​​的类。主要的是我需要添加自定义的auth标头,在用户授权后可用。

主要问题是令牌存储在Ionic Storage模块中,只能异步获取,但我需要返回特定类型....

return super.request(url, options)...

所以基本上我需要以某种方式将{{1}}放到存储的承诺中,并在获得该令牌时返回。

1 个答案:

答案 0 :(得分:5)

接近成为副本。 (找不到)

至少,答案可以适用于同一个问题。如果您想保留返回的Observable,则可以将Promisethis.storage.get)转换为Observable

之后,您可以使用flapMap之类的运算符来返回super.request的值。

注意:编译器不知道它现在正在返回Response,因此将返回类型更改为Observable<any>(仍会返回Response))

export class APIRequest extends Http {

    private storage : Storage;

    constructor (backend: XHRBackend, options: RequestOptions) {
        super(backend, options);

        this.storage = new Storage;
    }
    // any return type (will return Response object but compiler doesn't understand that)
    request(url: string|Request, options?: RequestOptionsArgs): Observable<any> {
        if (typeof url === 'string') {
            url = AppConfig.API_SERVER + url
        } else {
            url.url = AppConfig.API_SERVER + url.url
        }

        //convert the Promise to an Observable
        val storageObservable = Observable.fromPromise(this.sotrage.get('authToken'));

        // rxjs/add/operator/mergeMap
        return storageObservable.flatMap(token => {
            if (typeof url === 'string') {
                if (!options) {
                    options = {headers: new Headers()};
                }

                options.headers.set('Authorization', `Bearer ${token}`);
            } else {
                url.headers.set('Authorization', `Bearer ${token}`);
            }
            // the value that will be returned
            return super.request(url, options).catch(this.catchAuthError(this));
        }, err => {
            // throw some error
        })


    }
}

有用的链接: