Angular 1.x使用优化中的RxJs Observables

时间:2017-08-01 13:41:38

标签: angularjs rxjs

我正在使用RxJs创建一个Angular 1.6应用程序来扩展我的服务,但我觉得我创建的其中一个东西可以写得更好。

因此,我的列表功能获得了一个过滤器对象,可以通过其他服务或服务本身的主题进行更新。因此,我将它们结合起来并订阅它。

但是我希望在调用列表后更新公共Observable。但是.subscribe()后跟.next()感觉很奇怪。还有其他方法吗?

执行此操作的代码如下所示:

constructor(private $log: ILogService,
            private $q: IQService,
            private http: Http,
            private appConfig: AppConfig,
            private searchService: SearchService) {
  this.pagingSubject = new Subject<Page>();
  this.applicableMachinesSubject = new Subject<ApplicableMachineFilterResponse>(); // Will store all incoming http requests
  this.applicableMachine$ = Observable.from(this.applicableMachinesSubject);

  Observable
    .combineLatest(this.searchService.searchTermsHash$.throttleTime(250), this.pagingSubject)
    .share()
    .subscribe((next) => {
      // If less then 1 subscriber don't continue
      if (this.applicableMachinesSubject.observers.length < 1) {
        return;
      }
      const filter: ApplicableMachineFilter = assign(new ApplicableMachineFilter, next[0], next[1]);
      this.list(filter)
          .subscribe((f) => {
            this.applicableMachinesSubject.next(f);
          });
    });
}

private list(filter?: ApplicableMachineFilter): Observable<ApplicableMachineFilterResponse> {
  const validFilter: ApplicableMachineFilter = this.validate(filter);
  return this.http
             .get(`${this.appConfig.api}/ApplicableMachines`, {params: validFilter})
             .map((res) => (res as any).data);
}

我们重写了角度1的$ http服务以使用Observables

0 个答案:

没有答案