首页 > 解决方案 > 路由器重定向后订阅调用次数过多

问题描述

我有一个简单的组件,它从状态中选择一些东西并监听变化:

private items$: Observable<Item[]>;
private alive: boolean = true;

contructor(private store: Store<state>) {
  this.items$ = this.store.select(selectItems);
}

ngOnInit() {
  this.items$
    .pipe(
      takeWhile(() => this.alive)
    )
    .subscribe((items: Item[]) => {
      console.log('items changed!', items);
      // dispatch some actions
    });
}

ngOnDestroy() {
  this.alive = false;
}

它完美运行 - 每次项目更改时,我都会看到“项目已更改!” 记录的字符串。当我重定向到其他地方并且组件被销毁时,订阅不会运行。

但是当我重定向回组件并且订阅再次处于活动状态时,它会立即执行与开始时相同数量的更改,即使没有任何更改。

例如,当我进入页面时:

items changed! null
items changed! ['a', 'b', 'c']
items changed! ['a', 'b', 'c', 'd']

当我重定向并返回组件时:

items changed! ['a', 'b', 'c', 'd']
items changed! ['a', 'b', 'c', 'd']
items changed! ['a', 'b', 'c', 'd']

这里有什么问题?我已经尝试过takeUntil一个主题,我尝试手动取消订阅 - 没有解决问题。

标签: rxjsangular6

解决方案


对主题使用 takeUntil

private items$: Observable<Item[]>;
private finalised = new Subject<void>();

contructor(private store: Store<state>) {
  this.items$ = this.store.select(selectItems);
}

ngOnInit() {
  this.items$
    .pipe(
      takeUntil(this.finalised)
    )
    .subscribe((items: Item[]) => {
      console.log('items changed!', items);
      // dispatch some actions
    });
}

ngOnDestroy() {
  this.finalised.next();
  this.finalised.complete();
}

推荐阅读