首页 > 解决方案 > 使用 takeUntil 销毁 Angular Observable:当 ngOnDestroy 中缺少 .next() 时会发生什么

问题描述

在 Angular 7 组件中,我使用 RxJS takeUntil() 正确取消订阅可观察订阅。


@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();
    }
}

标签: angularrxjsobservableunsubscribe

解决方案


  1. takeUntil将 next 作为发射。如果只complete()调用它不会取消订阅

试试这个:

const a=new Subject();
interval(1000).pipe(takeUntil(a)).subscribe(console.log);
timer(3000).subscribe(_=>a.complete())
  1. this.destroy$仍在内存中,不会被垃圾收集
  2. 不是我知道

也请看这里以避免使用takeUntil.

https://medium.com/angular-in-depth/rxjs-avoiding-takeuntil-leaks-fb5182d047ef

就个人而言,我更喜欢unsubscribe在销毁时显式。


推荐阅读