使用RxJS CombineLatest过滤可观察对象?

时间:2018-09-27 19:59:50

标签: angular typescript rxjs stackblitz

我正在查看是否可以在Angular服务中使用combineLatest来移除activeFiler$开关块(该服务应该做同样的事情)。这是组件design right now (stackblitz link),我正在尝试删除所有render$除外的属性:

export class TodosComponent implements OnInit {
  constructor(private ts:TodoService) {}
  render$: Observable<Todo[]>; 
  activeFilter$: Observable<VISIBILITY_FILTER>;


ngOnInit() {
  this.render$ = this.ts.selectedTodos$;
  this.activeFilter$ = this.ts.activeFilter$;

  this.activeFilter$.subscribe(active=>{
        switch (active) {
    case VISIBILITY_FILTER.SHOW_COMPLETED:
      this.render$ = this.ts.completeTodos$;
      break;
    case VISIBILITY_FILTER.SHOW_ACTIVE:
      this.render$ = this.ts.incompleteTodos$;
      break;
    default:
      this.render$ = this.ts.todos$;
      }
  });
}
  }
}

如图所示,我已将this.render$初始化为从todo.service.ts文件返回的Observable。该方法如下所示:

  this.selectedTodos$ = 
  combineLatest(this.activeFilter$, this.completeTodos$, this.incompleteTodos$, this.todos$, this.applyFilter);

  private applyFilter(filter, completeTodos, incompleteTodos, todos): Todo[] {
    switch (filter) {
      case VISIBILITY_FILTER.SHOW_COMPLETED:
        return completeTodos;
      case VISIBILITY_FILTER.SHOW_ACTIVE:
        return incompleteTodos;
      default:
        return todos;
    }
  }

因此,在完成所有这些操作之后,我认为我应该能够删除todos组件中的this.ts.ostore.observe(ACTIVE_FILTER_KEY).subscribe(active=>{ 块,但是如果我删除了,则整个应用程序将停止工作。

一件奇怪的事是,如果我注释掉$activeFilter订阅并记录下来:

  this.render$ = this.ts.selectedTodos$;
  this.render$.subscribe(v=>console.log(v));

当我输入更多的待办事项时,它们会被记录下来,但是它们不会呈现...有任何想法吗?

1 个答案:

答案 0 :(得分:0)

我知道了。

使其工作的核心部分是,每个combineLatest至少发出一次时,Observable就会发出。

在我的情况下,ReplaySubject<Todo[]>实例在初始化EStore时没有执行通知,因此ReplaySubject<Todo[]>永远不会触发combinedLatest运算符

我更改了EStore的实现,以使其不发出任何内容或初始化EStore的实体,现在它可以正常工作。

   changeDetection: ChangeDetectionStrategy.OnPush

工作。我们不需要事件发射器或@Input使其起作用。只需查询商店,然后让它发挥作用即可。

相关问题