Ionic 2 - 从存储值获取令牌并在HTTP请求之前设置Header [英] Ionic 2 - Get token from Storage value and set Header before HTTP Request

查看:1005
本文介绍了Ionic 2 - 从存储值获取令牌并在HTTP请求之前设置Header的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用离子/存储程序包为用户登录后存储 api_token ,以便我可以使用唯一令牌与API进行交互。

I am using the ionic/storage package to store the api_token for users after they logged in so I can use the unique token to interact with an API.

我面临的问题是我需要通过 storage.get获取值返回一个promise并导致我想要设置的标题没有及时设置。

The problem I am facing is that I need to get the value via storage.get which returns a promise and results in the headers I want to set not being set in time.

我需要返回一个RequestOptions实例但是可以'弄清楚如何添加我从一个承诺来检索的标题。添加与localStorage同步的头文件在测试时工作正常,因此问题必须是异步执行。

I need to return an instance of RequestOptions but can't figure out how to add the header I retrieve when it comes from a promise. Adding a header synchronous with localStorage is working fine when testing so the issue must be the asynch execution.

createAuthorizationHeader(headers: Headers) {
    // this does add the header in time
    localStorage.setItem('api_token', 'some token');
    headers.append('Authorization', 'Bearer ' + localStorage.getItem('api_token'));

    // this does not add the header in time
    return this.storage.get('api_token').then((value) => {
        headers.append('Authorization', 'Bearer ' + value);
    });
}

getHeaders(path): RequestOptions {
    let headers = new Headers({
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    });

    if(!this.isGuestRoute(path)) {
        this.createAuthorizationHeader(headers);
    }

    return new RequestOptions({ headers: headers });
}

get(path: string) {
    return this._http.get(this.actionUrl + path, this.getHeaders(path))
        .map(res => res.json())
        .catch(this.handleError);
}

编辑:工作代码现在看起来像这样

getApiToken(): Observable<Headers> {
    return Observable.fromPromise(this.storage.get('api_token'));
}

getHeaders(): Headers {
    return new Headers({
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    });
}

get(path: string) {
    let headers: Headers = this.getHeaders();

    if(!this.isGuestRoute(path)) {
        return this.getApiToken().flatMap(data => {
            headers.append('Authorization', 'Bearer' + data);

            return this._http.get(this.actionUrl + path, { headers : headers })
                .map(res =>  res.json())
                .catch(this.handleError);
        });
    }

    return this._http.get(this.actionUrl + path, { headers : headers })
        .map(res => res.json())
        .catch(this.handleError);
}


推荐答案

查看我的类似问题< a href =https://stackoverflow.com/questions/40613099/angular2-use-value-of-observable-returning-method-in-another-observable> Angular2 - 在另一个Observable中使用Observable返回方法的值

如果将Promise转换为 Observable ,您将可以使用rxjs flatMap 功能。

If you convert the Promise to a Observable you will be able to use the rxjs flatMap function.

让我告诉你看起来有点像什么

Let me show you what your would somewhat look like then

getApiToken(): Observable<Headers> {
    return Observable.fromPromise(this.storage.get('api_token'));
   //OR return Observalbe.of(this.storage.get('api_token'));
}

getHeaders(): Headers { 
     //create all headers here except the 'api_token'
     .....
}


get(path: string): Observable<any> {
    let headers: Headers = this.getHeaders();
    return this.getApiToken().flatMap(data => {

       headers.append('Authorization', 'Bearer'+data);

       return this.http.get(this.actionUrl + path, headers)
          .map(res =>  res.json()) 
          .catch(this.handleError);
    });
}

或者(刚刚了解了这一点,所以不确定它是否可行)

OR (Just learned about this so not sure if it will work)

createAuthorizationHeader(headers: Headers) {
    // this does add the header in time
    localStorage.setItem('api_token', 'some token');
    headers.append('Authorization', 'Bearer ' + localStorage.getItem('api_token'));

    // this does not add the header in time
    let api_token = await this.storage.get('api_token');
    headers.append('Authorization', 'Bearer ' + api_token);
}

这篇关于Ionic 2 - 从存储值获取令牌并在HTTP请求之前设置Header的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆