取消订阅 Angular NGXS
Unsubscribing in Angular NGXS
我是 Angular 的 NGXS 新手,我了解到使用异步管道时不需要取消订阅。但是,我也从 queryParams 订阅并且我从 dispatches 操作订阅。我需要取消订阅下面的这 2 个代码吗?
this.route.queryParamMap
.pipe(map(params => params.get('page')))
.subscribe((page: any) => {
this.page = page;
console.log(page);
});
this.store.dispatch(new AddEmployee(form.value)).subscribe(() => {
form.reset();
this.modalReference.close();
这很简单。您需要描述一个 Subject
并在 ngOnDestroy
生命周期中调用它。您还应该在提供的 Subject
.
上使用 takeUntil
管道
destroy$ = new Subject<void>();
ngOnInit(): void {
this.service.observable$.pipe(
takeUntil(this.destroy$)
).subscribe();
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
当 observable 多次发出值时,最好使用此方法。
例如,如果您使用 this.router.events.subscribe
,即使组件已被销毁,它也会触发事件,除非您使用上面显示的方法。
答案是不需要退订这两组代码。
因为路由由 Angular 处理,其次,商店由 ngxs 处理。无需退订。仅在使用 rxjs
时退订
GitHub: Does I need to unsubscribe on distaching actions?
amcdnl commented on Jul 3, 2018
Nope. Its handled for you.,
所以我不确定 NGXS 本身是否会为我们处理任何 complete
。现在都是基本的 RxJS 标准。
从@Joseph 的回答中的 link,@Mark Whitfield 指出:
If you subscribe to the observable then you need to make sure that you unsubscribe.
切片数据
在没有订阅的情况下分派存储 Action 将是一个“冷”可观察对象。 无需取消订阅。
this.store.dispatch(new FetchStatuses()); // Cold
异步管道由 NGXS 和/或 Angular 的异步管道模式处理
// controller
@Select(SomeState.scope) scope$!: Observable<any>;
// view
<p-dropdown [options]="scope$ | async" ...
但是,这种调度场景显然需要取消订阅
this.store.dispatch(new AddAnimal(name)) // Hot
.subscribe(res) => {
// Hot observable, alive until manually completed
});
我是 Angular 的 NGXS 新手,我了解到使用异步管道时不需要取消订阅。但是,我也从 queryParams 订阅并且我从 dispatches 操作订阅。我需要取消订阅下面的这 2 个代码吗?
this.route.queryParamMap
.pipe(map(params => params.get('page')))
.subscribe((page: any) => {
this.page = page;
console.log(page);
});
this.store.dispatch(new AddEmployee(form.value)).subscribe(() => {
form.reset();
this.modalReference.close();
这很简单。您需要描述一个 Subject
并在 ngOnDestroy
生命周期中调用它。您还应该在提供的 Subject
.
takeUntil
管道
destroy$ = new Subject<void>();
ngOnInit(): void {
this.service.observable$.pipe(
takeUntil(this.destroy$)
).subscribe();
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
当 observable 多次发出值时,最好使用此方法。
例如,如果您使用 this.router.events.subscribe
,即使组件已被销毁,它也会触发事件,除非您使用上面显示的方法。
答案是不需要退订这两组代码。 因为路由由 Angular 处理,其次,商店由 ngxs 处理。无需退订。仅在使用 rxjs
时退订GitHub: Does I need to unsubscribe on distaching actions?
amcdnl commented on Jul 3, 2018
Nope. Its handled for you.,
所以我不确定 NGXS 本身是否会为我们处理任何 complete
。现在都是基本的 RxJS 标准。
从@Joseph 的回答中的 link,@Mark Whitfield 指出:
If you subscribe to the observable then you need to make sure that you unsubscribe.
切片数据
在没有订阅的情况下分派存储 Action 将是一个“冷”可观察对象。 无需取消订阅。
this.store.dispatch(new FetchStatuses()); // Cold
异步管道由 NGXS 和/或 Angular 的异步管道模式处理
// controller
@Select(SomeState.scope) scope$!: Observable<any>;
// view
<p-dropdown [options]="scope$ | async" ...
但是,这种调度场景显然需要取消订阅
this.store.dispatch(new AddAnimal(name)) // Hot
.subscribe(res) => {
// Hot observable, alive until manually completed
});