我们应该退订ngxs Selector吗?

时间:2019-06-11 08:07:13

标签: angular ngxs

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

mqsichangeproperties IBNODE -o BrokerRegistry -n crlFileList -v file_path

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

是的,如果您手动订阅该组件,则需要退订。

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

答案 2 :(得分:1)

异步管道解决方案通常是最好的。

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

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

它比takeUntil方法要短,并且您不需要取消订阅。

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

当心:这将返回一个值并取消订阅。因此,如果您需要存储中的当前值,然后对其进行处理,则可以使用它。不要使用它在GUI上显示内容-它只会显示第一个更改:)

相关问题