【发布时间】:2020-02-14 03:34:02
【问题描述】:
有几种方法可以取消订阅 Angular 组件上的 observables(使用 ngOnDestroy)。应该首选以下哪个选项以及为什么(例如技术原因、性能等)?
选项 1:采取Until
使用 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();
}
}
选项 2:.unsubscribe()
显式调用 .unsubscribe(),例如通过使用单独的订阅实例
@Component({
selector: "app-flights",
templateUrl: "./flights.component.html"
})
export class FlightsComponent implements OnDestroy, OnInit {
private readonly subscriptions = new Subscription();
public flights: FlightModel[];
constructor(private readonly flightService: FlightService) {}
ngOnInit() {
const subscription = this.flightService
.getAll()
.subscribe(flights => (this.flights = flights));
this.subscriptions.add(subscription);
}
ngOnDestroy() {
this.subscriptions.unsubscribe();
}
}
选项 3:takeWhile
使用 RxJS takeWhile 取消订阅
选项 n:?
【问题讨论】:
-
你可以问十个人,他们都有自己的喜好。您提到的所有选项都是完全有效的,并且没有明确的“最佳”选项。 IMO takeUntil 是最好的解决方案。
-
好的,我想知道一个或另一个选项是否有技术原因...感谢您的评论
-
@HoraceP.Greeley 我知道已经晚了,但为什么需要 this.destroy$.next();在选项 1 上?
-
@raberana next() 是必需的,因为“takeUntil”通过调用 destory$.next() 直到 destroy$ 具有值。另一个主题,但很重要:takeUntil 应该在管道中的最后一个位置。见cartant.medium.com/rxjs-avoiding-takeuntil-leaks-fb5182d047ef
标签: angular rxjs observable unsubscribe