从承诺内部返回已解决的观察结果

时间:2016-11-30 22:20:29

标签: angular typescript local-storage ionic2

我正在尝试通过扩展默认值来构建自定义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/

1 个答案:

答案 0 :(得分:13)

我不知道该存储是否返回与Rx兼容的承诺,但如果是,那么解决方案应如下所示:

function myFunction() {
  try
  {
    var a = ""
    for (i =  0; i< 50000; i++)
       a += '111'
       SpreadsheetApp.open(DriveApp.getFileById("FileID")).getActiveSheet().getRange(1,1).setValue(a);
       SpreadsheetApp.flush();
  }
  catch (e)
  {
     Logger.log(e.message)
  }
}

如果承诺与可观察者不相容,那么仍然有办法做到这一点,尽管它并不那么优雅:

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

        });
    });

}