我们应该退订ngxs Selector吗?

Tam*_*ien 5 angular ngxs

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

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

this.list$.subscribe((data) => console.log(data));
Run Code Online (Sandbox Code Playgroud)

Scu*_*Kay 6

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

在您的ts文件中:

@Select(list) list: Observable<any>;
Run Code Online (Sandbox Code Playgroud)

在您的html文件中:

<ng-container *ngFor="let item of list | async">
</ng-container>
<!-- this will unsub automatically -->
Run Code Online (Sandbox Code Playgroud)

但是,当您想使用实际的订阅方法时,将需要手动取消订阅。最好的方法是使用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();
  }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 我同意斯库巴凯的观点。这正是我们在企业项目中所做的。 (2认同)