[英]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 在 NGXS 狀態初始化后被解析。 它們由導入到 AppModule 中的 NgxsModule 初始化。 在解析 APP_INITIALIZER 令牌之前,還會調用狀態上的 ngxsOnInit 方法。
上面的代碼按預期工作,但 typescript 錯誤仍然發生。 有什么解決方法嗎?
此外,我決定不對 typescript 開源項目提出問題,因為它也可能與 NgXs 生命周期本身有關。
如果你想在.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
是一個純 function 接收 state 並返回給定子狀態。
這是文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.