角度 – 从承诺内部返回已解决的观察值

我正在尝试通过扩展认值来构建自定义Angular 2 http请求,并且我正在使用Ionic 2本地存储来存储身份验证令牌. (将来可能会使用文件系统).我的问题是如何从我的http服务返回已解析的promise,以便我可以在我的组件中订阅Observable.我试过Observable.fromPromise和其他变种无济于事.
request(url: string|Request,options?: RequestOptionsArgs): Observable<Response> {

  // Get the token used for this request.
  // * Need to return this promise resolved.
  var promise = this.storage.get('token').then(token => {

    if (typeof url === 'string') { // meaning we have to add the token to the options,not in url
      if (!options) {
        // let's make option object
        options = {headers: new Headers()};
      }
      options.headers.set('Authorization','Basic ' + token);
    } else {
    // we have to add the token to the url object
      url.headers.set('Authorization','Basic ' + token);
    }

    return super.request(url,options).catch(this.catchAuthError(this));

  }).catch(error => {
    console.log(error);
  });

}

Idea基于这篇博客文章,但Ionic存储返回了一个承诺. http://www.adonespitogo.com/articles/angular-2-extending-http-provider/

我不知道该存储是否返回与Rx兼容的promise,但如果是,则解决方案应如下所示:
request(url: string|Request,options?: RequestOptionsArgs): Observable<Response> {

    return Observable
        .fromPromise(this.storage.get('token'))
        .flatMap(token => {

            if (typeof url === 'string') { // meaning we have to add the token to the options,not in url
                if (!options) {
                    // let's make option object
                    options = {headers: new Headers()};
                }
                options.headers.set('Authorization','Basic ' + token);
            } else {
                // we have to add the token to the url object
                url.headers.set('Authorization','Basic ' + token);
            }

            return super.request(url,options).catch(this.catchAuthError(this));

        });
    });

}

如果promise与observable不兼容,那么还有一种方法可以做到这一点,尽管它并不那么优雅:

request(url: string|Request,options?: RequestOptionsArgs): Observable<Response> {

    return Observable.create((observer: Observer) => {

        this.storage.get('token').then(token => {

            if (typeof url === 'string') { // meaning we have to add the token to the options,'Basic ' + token);
            }

            super.request(url,options).catch(this.catchAuthError(this)).subscribe(result => {
                observer.next(result);
                observer.complete();
            });

        }).catch(error => {
            observer.error(error);
        });

    });

}

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...