Angular 2.0 - 将承诺链转换为Observables

时间:2015-12-24 12:50:36

标签: javascript angularjs reactive-programming angular rxjs

我正在将NG 1.X服务转换为NG 2.0。

我的NG 1.X服务承诺链接(简化):

dataService.search = function(searchExp) {
      return this.getAccessToken()
      .then(function(accesstoken) {
        var url = $interpolate('https://my-api-url?q={{search}}&{{accesstoken}}')({search: searchExp, accesstoken: accesstoken});
        return $http({
          url: url,
          method: 'GET',
          cache: true
        });
      }).then(function(response) {
        return response.data;
      });
    };

我想使用search并返回httpObservable服务转换为Angular 2.0服务。我更喜欢保持getAccessToken服务不变,作为NG 1.X服务,它返回一个承诺。

我正在考虑在旧的"承诺上使用Observable.fromPromise"服务。

我该怎么办?我该如何将这两者联系起来?

修改

只是为了澄清,我希望它是这样的:

dataService.search = function(searchExp) {
 return this.getAccessToken()
        .then(function(accesstoken) {
           //Here I want to use:
           // this.http.get(url).subscribe(() => ...)
          });
        };

2 个答案:

答案 0 :(得分:8)

您应该使search方法返回Observable对象。像这样:

dataService.search = function(searchExp) {

    var promise = new Promise((resolve, reject) => {
        this.getAccessToken()
            .then(accesstoken => {
                return this.http.get('data.json')
                    .map(response => response.json())
                    .subscribe(data => resolve(data), err => reject(err))
            })
    });

    return PromiseObservable.create(promise); // Observable.fromPromise(promise)
};

答案 1 :(得分:3)

我将@ dfsq&#39的Plunker转换为beta.0。 map()在没有导入的情况下似乎不再可用(但我们在这里不需要它)。

import {Component, Injectable} from 'angular2/core';
import {HTTP_PROVIDERS, Http} from 'angular2/http';
import {PromiseObservable} from 'rxjs/observable/fromPromise';

@Injectable()
export class DataService {
  constructor(private _http: Http, private _accessService: AccessService) {} 
  search(searchExp) {
    var promise = new Promise((resolve, reject) => {
      this._accessService.getAccessToken()  // see Plunker for AccessService
        .then(accessToken => {
          return this._http.get('data.json')  // use accessToken here
            .subscribe(res => resolve(res.json()), err => reject(err));
        });
    });
    return PromiseObservable.create(promise);
  }
}
@Component({
  selector: 'my-app',
  providers: [HTTP_PROVIDERS, AccessService, DataService],
  template: `<h2>Data loaded</h2><pre>{{data | json}}</pre>
  `
})
export class AppComponent {
  data: any;
  constructor(private _dataService: DataService) { 
    console.clear();
  } 
  ngOnInit() {
    this._dataService.search('test')
      .subscribe(res => {
        this.data = res; 
      });
  }
}

beta.0 Plunker