来自父组件中服务器的初始状态

Initial state from server in parent component

我正在查看 ngrx example app and trying to figure out a good way to initialize state on the find page (http://localhost:4200/#/books/find)。

看来我应该可以将它添加到 AppComponent

ngOnInit() { 
    this.store.dispatch(new book.Search('Michael Jordan')); 
}

但这并没有填充 FindBookPageComponent 中的商店 它似乎在链条中发生得太早了。 想知道是否有人可以解释这一点并提供更好的方法。

注意: 将 ngOnInit 添加到 FindBookPageComponent 是可行的,但每次用户导航回来时都会调用它。如果有意义的话,我希望这更像是一个初始状态。

谢谢!

最好放在router guards => canActivate()

检查存储中是否存在数据;否则分派负载数据

canActivate(): Observable<boolean> {
  return this.checkStore().pipe(
    switchMap(() => of(true)),
    catchError((error) => of(false))
    );
}

checkStore(): Observable<boolean> {
  return this.store.select(fromStore.getDataLoaded).pipe(
    tap(loaded => {
      if (!loaded) {
        this.store.dispatch(new fromStore.LoadDataCollection());
      }
    }),
    filter(loaded => loaded),
    take(1)
    );
}