angular - 使用 takeUntil 销毁 Angular Observable:当 ngOnDestroy 中缺少 .next() 时会发生什么
问题描述
在 Angular 7 组件中,我使用 RxJS takeUntil() 正确取消订阅可观察订阅。
- 当
this.destroy$.next()
方法中缺少时会发生什么ngOnDestroy
(参见下面的示例)?它仍然会正确退订吗? - 当
this.destroy$.complete()
方法中缺少时会发生什么ngOnDestroy
(参见下面的示例)?它仍然会正确退订吗? - 有什么方法可以强制使用 takeUntil() 来取消订阅的模式被正确使用(例如 tslint 规则、npm 包)?
@Component({
selector: 'app-flights',
templateUrl: './flights.component.html'
})
export class FlightsComponent implements OnDestroy, OnInit {
private readonly destroy$ = new Subject();
public flights: FlightModel[];
constructor(private readonly flightService: FlightService) { }
ngOnInit() {
this.flightService.getAll()
.pipe(takeUntil(this.destroy$))
.subscribe(flights => this.flights = flights);
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
}
解决方案
takeUntil
将 next 作为发射。如果只complete()
调用它不会取消订阅
试试这个:
const a=new Subject();
interval(1000).pipe(takeUntil(a)).subscribe(console.log);
timer(3000).subscribe(_=>a.complete())
this.destroy$
仍在内存中,不会被垃圾收集- 不是我知道
也请看这里以避免使用takeUntil
.
https://medium.com/angular-in-depth/rxjs-avoiding-takeuntil-leaks-fb5182d047ef
就个人而言,我更喜欢unsubscribe
在销毁时显式。
推荐阅读
- c# - Google Speech API - 可以获得音素成绩单吗?
- regex - 一个正则表达式可进行 0、1 或 n 次文本替换
- html - 如何将模型中的项目显示为视图中的链接
- composer-php - 无法在 Artifactory 包视图中选择 PHP Composer
- javascript - 将两个不同的关联数组放在一个关联数组中,作为一个在javascript中具有两个关联数组的数组
- python - 使用列名和 dtypes 加载 pandas 表
- twilio - Twilio statusCallback 不会触发
- r - glmulti:为具有两个嵌套随机变量的 glmer 分配预测函数
- regex - 正则表达式 - 如何在动态文件夹名称中查找文件
- nginx - 在 aws ec2 Linux 内核 4.14 实例上的 ansible 上安装 nginx 时出错