【发布时间】:2020-02-14 00:14:27
【问题描述】:
在 Angular 7 组件中,我使用 RxJS takeUntil() 正确取消订阅可观察订阅。
- 当方法
ngOnDestroy中缺少this.destroy$.next()时会发生什么(参见下面的示例)?还能正常退订吗? - 当
ngOnDestroy方法中缺少this.destroy$.complete()时会发生什么情况(参见下面的示例)?还能正常退订吗? - 有什么方法可以强制使用 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();
}
}
【问题讨论】:
标签: angular rxjs observable unsubscribe