在自定义服务中通过promise Angular获取值

时间:2017-05-12 10:04:56

标签: javascript angular promise angular2-services

我有这段代码:

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Storage } from '@ionic/storage';
import { AppSettings } from './shared';

@Injectable()
export class HttpClient {

    constructor(private http: Http, private storage: Storage) { }

    createAuthorizationHeader(headers: Headers) {
        var token: string = '';
        this.storage.get(AppSettings.StorageKeys.Token).then(value => {
            token = value;
        });
        headers.append('Authorization', 'Bearer ' + token);
    }

    get(url) {
        let headers = new Headers();
        this.createAuthorizationHeader(headers);
        return this.http.get(url, {
            headers: headers
        });
    }

    post(url, data) {
        let headers = new Headers();
        this.createAuthorizationHeader(headers);
        return this.http.post(url, data, {
            headers: headers
        });
    }
}

这里的问题是:

this.storage.get(AppSettings.StorageKeys.Token).then(value => {
            token = value;
        });

这是承诺。那么如何更改createAuthorizationHeader函数,以便正确附加标题?

这是Ionic2代码,但大多数问题与承诺的工作有关。

2 个答案:

答案 0 :(得分:2)

返回标头承诺,然后从该承诺链接http调用。同样get方法应该在Observable之前返回承诺,因为您可以.toPromise()使用http.get方法。

createAuthorizationHeader() {
    return this.storage.get(AppSettings.StorageKeys.Token).then(value => {
        let headers = new Headers();
        var token: string = '';
        token = value;
        headers.append('Authorization', 'Bearer ' + token);
        return headers;
    });
}

get(url) {
    //let headers = new Headers();
    return this.createAuthorizationHeader().then(headers => {
        return this.http.get(url, { headers: headers }).toPromise();
    });
}

post函数执行相同操作。

  

我会失去Observable并且必须与承诺合作。

如果您希望使用observables,请在链接两个承诺后转换承诺:

get(url) {
    //let headers = new Headers();
    var promise = this.createAuthorizationHeader().then(headers => {
        return this.http.get(url, { headers: headers }).toPromise();
    });
    return Observable.fromPromise(promise);
}

答案 1 :(得分:2)

createAuthorizationHeader不返回承诺,您应该从承诺功能成功创建Authorization令牌。此外,get您的服务应该返回承诺,同样,您可以使用.toPromise()返回promise,尽管Observable。但是,由于您没有赢得可观察到的酱油,您应该考虑将createAuthorizationHeader方法转换为返回ObservableObservable.fromPromise会在这种情况下拯救我们,将Promise转换为Observable

<强>代码

createAuthorizationHeader(headers: Headers) {
    var token: string = '';
    let headers = new Headers();
    return Observable.fromPromise(this.storage.get(AppSettings.StorageKeys.Token)
      .then(value => {
        token = value;
        headers.append('Authorization', 'Bearer ' + token);
        return headers;
      }
    );
}

get(url) {
    return this.createAuthorizationHeader()
     .switchMap((headers)=> this.http.get(url, {
        headers: headers
      });
    })
}