NGXS:属性 'stream$' 在初始化之前使用

NGXS: Property 'stream$' is used before its initialization

乍一看,这似乎是 angular 组件生命周期逻辑的默认行为,因为组件属性尚未初始化,所以 stream$ 无法在组件初始化完成之前进行赋值:

@Component({
  selector: 'app-component',
  template: `<p>app works!</p>`,
})
export class AppComponent implements OnInit {
  @Select(AppState.getItems)
  stream$: Observable<string[]>;

  firstItemStream$: Observable<{ selectedItem: string }> = this.stream$ // error occurs here
  .pipe(
    find(({ itemId }) => itemId === 0),
  );

  ...

引自 NgXs:

APP_INITIALIZER is resolved after NGXS states are initialized. They are initialized by the NgxsModule that is imported into the AppModule. The ngxsOnInit method on states is also invoked before the APP_INITIALIZER token is resolved.

以上代码按预期工作,但仍然出现打字稿错误。有什么解决方法吗?

我还决定不向 typescript 开源项目提出问题,因为它也可能与 NgX 的生命周期本身有关。

如果您想在 .ts 代码中使用 stream$ 作为另一个来源,您需要像这样定义 属性:

@Component({
  selector: 'app-component',
  template: `<p>app works!</p>`,
})
export class AppComponent implements OnInit {
  stream$: Observable<string[]>;
  firstItemStream$: Observable<{selectedItem: string}>;

  constructor(private readonly _store: Store) {
    this.stream$ = this.store.select(AppState.getItems);
    this.firstItemStream$ = this.stream$
      .pipe(
        find(({itemId}) => itemId === 0),
      );
  }
}

注意:我假设 AppState.getItems 是一个接收状态和 returns 给定子状态的纯函数。

这里是the documentation

这听起来像是 this 使用 select 装饰器的场景。

因此您需要将声明更新为:

@Select(AppState.getItems) stream$!: Observable<string[]>;