选择器 NGRX 内的调度操作

Zim*_*ger 2 rxjs typescript redux ngrx angular

在我的选择器中,我正在检查存储中的数据是否已加载并对应于路由器参数。路由器是“事实来源”,因此如果未加载数据,我想发送一个操作来获取它。在选择器中做这样的事情可以吗?

  (currentGameState, router): Game => {
     if (currentGameState.game.id === router.state.params.gameId && 
         currentGameState.isLoaded) {
         return currentGameState.game;
     }
  }
Run Code Online (Sandbox Code Playgroud)

Ton*_*Ngo 6

副作用由效果类处理(调度操作、调用 api 等)。

选择器仅用于使用异步从存储中获取数据。这意味着不要在这里做任何像调度操作这样的副作用。

正常更新你需要在 ngOnInit 中初始化数据加载

export class PostComponent implements OnInit {
  public posts$: Observable<IPost[]>;
  constructor(private store: Store<IPostManagementState>) {}
  ngOnInit(): void {
    this.store.dispatch(new GetAllPosts());
    this.posts$ = this.store.pipe(select(selectPostList));
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在视图中使用异步管道

<div *ngFor="let post of posts$ | async">{{ post.body }}</div>
Run Code Online (Sandbox Code Playgroud)

您可以在此处查看代码

  • 在这种情况下,启动数据加载的最佳位置是什么? (2认同)