【问题标题】:Should we unsubscribe from ngxs Selector?我们应该取消订阅 ngxs Selector 吗?
【发布时间】:2019-10-25 14:35:39
【问题描述】:

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

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

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

【问题讨论】:

标签: angular ngxs


【解决方案1】:

对于第一个示例,您可以与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()

【讨论】:

  • 我同意 Scuba Kay 的观点。这正是我们在企业项目中所做的。
【解决方案2】:

是的,如果您在组件中手动订阅,则需要取消订阅。

如果可能,最好避免这种情况,并使用async 管道订阅组件模板。

【讨论】:

    【解决方案3】:

    Async Pipe 解决方案通常是最好的。

    根据您的用例,您还可以使用 first() 运算符。

    observable.pipe(first()).subscribe(...)
    

    它比 takeUntil 方法更短,您不需要任何退订。

    https://www.learnrxjs.io/operators/filtering/first.html

    注意:这将返回一个值并取消订阅。因此,如果您需要来自商店的当前值,然后对其进行处理,则可以使用它。不要用它在 GUI 上显示一些东西——它只会显示第一个变化:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-22
      • 2012-05-30
      • 1970-01-01
      • 1970-01-01
      • 2018-12-05
      • 1970-01-01
      相关资源
      最近更新 更多