首页 > 解决方案 > 我们应该取消订阅 ngxs Selector 吗?

问题描述

我正在使用 ngxs 状态管理。我需要取消订阅选择器还是由 ngxs 处理?

@Select(list)list$!: Observable<any>;

this.list$.subscribe((data) => console.log(data));

标签: angularngxs

解决方案


对于第一个示例,您可以与Async pipe结合使用。异步管道将为您取消订阅:

在您的ts文件中:

@Select(list) list: Observable<any>;

在您的html文件中:

<ng-container *ngFor="let item of list | async">
</ng-container>
<!-- this will unsub automatically -->

但是,当您想使用实际的订阅方法时,您需要手动取消订阅。最好的方法是使用takeUntil

import {Subject} from 'rxjs';
import {takeUntil} from 'rxjs/operators';

@Component({
  selector: 'app-some-component',
  templateUrl: './toolbar.component.html',
  styleUrls: ['./toolbar.component.scss']
})
export class SomeComponent implements OnInit, OnDestroy {
  private destroy: Subject<boolean> = new Subject<boolean>();

  constructor(private store: Store) {}

  public ngOnInit(): void {
    this.store.select(SomeState).pipe(takeUntil(this.destroy)).subscribe(value => {
      this.someValue = value;
    });
  }

  public ngOnDestroy(): void {
    this.destroy.next(true);
    this.destroy.unsubscribe();
  }
}

您可以pipe(takeUntil(this.destroy))为组件中的每个订阅使用,而无需为每个订阅手动添加unsubscribe()


推荐阅读