如何在组件中使用@ngrx/store?

How to use @ngrx/store in component?

我阅读 the documentation 后的理解是,为了从 NgRx 存储中获取值,我们必须使用选择器。到目前为止,我很幸运地做到了这一点,只是遇到了一个关于打字的小问题,这让我担心我的实现是否有任何不正确的地方。

所以,假设我想从商店中检索一个数字值,例如 id。在我的 componentName.component.ts 中,我会像这样访问这个值:

id$ = this.store.select(selectId);

其中 selectId 从另一个文件定义为:

export const selectData = (state: AppState) => state.data;

export const selectId = createSelector(
  selectData,
  (state: DataState) => state.id,
)

我可以通过 {{id$ | async}} 轻松访问我的 HTML 组件中的 id$,但事实证明从组件 class 本身访问它有点困难.对于初学者来说,变量类型是 Observable<number> 而不是 number,这使得在需要 number 类型的情况下很难使用它,例如比较它时:

  ngOnInit(): void {
    console.log(this.id$ === 0);
  }

我从上面的代码中得到的 TypeScript 错误是:

TS2367: This condition will always return 'false' since the types 'number' and 'Observable ' have no overlap.

并且控制台日志记录 id$ 本身确认它确实是 Observable 类型,所以这让我相信我做错了什么,但我不确定到底是什么。感谢任何帮助!!!

id$ 是一个 Observable,您可以通过使用 subscribe 函数从组件 class 订阅它来访问它的值,或者从组件模板使用async 管道。

在组件 Class 中:

ngOnInit(): void {
  this.id$.subscribe(id => console.log(id));
}

在组件模板中:

<span>{{ id$ | async }}</span>

查看Angular关于Observable(s)的官方文档:

https://angular.io/guide/observables