Angular takeUntil的角度可观测破坏:Ngondestory中缺少.next()时会发生什么
在Angular 7组件中,我使用RxJS takeUntil()来正确地取消可观察订阅Angular takeUntil的角度可观测破坏:Ngondestory中缺少.next()时会发生什么,angular,rxjs,observable,unsubscribe,Angular,Rxjs,Observable,Unsubscribe,在Angular 7组件中,我使用RxJS takeUntil()来正确地取消可观察订阅 当方法ngondestory中缺少this.destroy$.next()时会发生什么情况(请参见下面的示例)?它还会正常退订吗 当方法ngondestory中缺少this.destroy$.complete()时会发生什么情况(请参见下面的示例)?它还会正常退订吗 是否有任何方法可以强制使用takeUntil()来取消订阅的模式(例如,tslint规则、npm包) @组成部分({ 选择器:“应用程序
- 当方法
中缺少ngondestory
时会发生什么情况(请参见下面的示例)?它还会正常退订吗this.destroy$.next()
- 当方法
中缺少ngondestory
时会发生什么情况(请参见下面的示例)?它还会正常退订吗this.destroy$.complete()
- 是否有任何方法可以强制使用takeUntil()来取消订阅的模式(例如,tslint规则、npm包)
@组成部分({
选择器:“应用程序飞行”,
templateUrl:“./flights.component.html”
})
导出类FlightsComponent实现OnDestroy,OnInit{
私有只读销毁$=新主题();
公共航班:FlightModel[];
构造函数(专用只读flightService:flightService){}
恩戈尼尼特(){
this.flightService.getAll()
.pipe(takeUntil(此.destroy$))
.订阅(航班=>this.flights=航班);
}
恩贡德斯特罗(){
this.destroy$.next();
此.destroy$.complete();
}
}
takeUntil
将下一个作为排放。如果只调用complete()
,它将不会取消订阅const a=new Subject();
interval(1000).pipe(takeUntil(a)).subscribe(console.log);
timer(3000).subscribe(_=>a.complete())
此.destroy$
仍在内存中,无法回收垃圾takeUntil
时,请查看此处以避免内存泄漏
就我个人而言,我更喜欢在销毁时显式取消订阅。此.destroy$.next()
触发主题,该主题触发完成flightService.getAll()订阅的takeUntil
操作符
this.destroy$.complete()
完成组件销毁时的destroy$
主题。使用takeWhile代替takeUntil
@Component({
selector: 'app-flights',
templateUrl: './flights.component.html'
})
export class FlightsComponent implements OnDestroy, OnInit {
private readonly destroy$ = new Subject();
alive = true;
public flights: FlightModel[];
constructor(private readonly flightService: FlightService) { }
ngOnInit() {
this.flightService.getAll()
.pipe(takeWhile(() => this.alive))
.subscribe(flights => this.flights = flights);
}
ngOnDestroy() {
this.alive = false;
this.destroy$.complete();
}
}
这里有一个更简单的方法:
private readonly destroy$ = new Subject<boolean>();
...
ngOnDestroy() {
this.destroy$.next(true);
this.destroy$.unsubscribe();
}
private readonly destroy$=new Subject();
...
恩贡德斯特罗(){
this.destroy$next(true);
此.destroy$.unsubscribe();
}
Use:)您可能不需要主题的类型声明