rxjs - 路由器重定向后订阅调用次数过多
问题描述
我有一个简单的组件,它从状态中选择一些东西并监听变化:
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
一个主题,我尝试手动取消订阅 - 没有解决问题。
解决方案
对主题使用 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();
}
推荐阅读
- python - 通过检查标志循环
- javascript - JQuery load() 状态没有意义
- python - 使用 Python 中的嵌套列表推导从 mongo 集合中获取所有文档
- amazon-web-services - 是否可以未经身份验证访问 AWS Location 'Places' API?
- r - R - 使用嵌套列表选择最佳的行组合(蛮力)
- r - 在 R 中通过多个组使用卡方
- python - 我需要帮助来优化 Sum 3 问题的代码速度
- r-markdown - 如何使用 bookdown 将执行摘要放在 TOC 之前?
- python - Python Pandas 日期转换问题
- azure - Azure KeyVault 从 c# 启用或禁用密钥