简体   繁体   English

如何使用 Angular 9 和 NGRX 获取子组件中的数据?

[英]How to get data in Child Components using Angular 9 and NGRX?

I am creating a project with Angular 9 and NGRX and I have the following page component:我正在使用 Angular 9 和 NGRX 创建一个项目,并且我有以下页面组件:

@Component({
  template: `
    <div *ngFor="let post of posts$ | async">
      {{ post.name }}
    </div>
    <top-posts></top-posts>
  `
})
export class PostsPageComponent {

  posts$: Observable<Post[]> = this.store.select(state => state.posts);

  constructor(private store: Store<{ posts: Post[] }>) {}

  ngOnInit() {
    this.store.dispatch({ type: '[Posts Page] Load Posts' });
  }

}

In this component I have a Child Component that displays TopPosts.在这个组件中,我有一个显示 TopPosts 的子组件。

I believe I should add topPosts: Post[] to my Store and an action '[Posts Page] Load Top Posts'.我相信我应该将topPosts: Post[]添加到我的商店和一个操作“[帖子页面]加载热门帖子”。

But how should I access this data in my child component?但是我应该如何在我的子组件中访问这些数据?

  1. Should I inject the store in child component and use:我应该在子组件中注入商店并使用:

     this.store.dispatch({ type: '[Posts Page] Load Top Posts' });
  2. Should I pass the data from PostPageComponent into TopPostsComponent?我应该将 PostPageComponent 中的数据传递到 TopPostsComponent 吗?

    How?如何? And in this case should I change action to '[Top Posts Component] Load Top Posts'?在这种情况下,我应该将操作更改为“[Top Posts Component] Load Top Posts”吗?

In my opinion, you can dispatch the actions for your child components in the parent component and pass the result as @Input to your child components.在我看来,您可以在父组件中为您的子组件调度操作,并将结果作为@Input 传递给您的子组件。

This way your child component need not have any dependency on the store and can act as presentational components.这样,您的子组件就不需要对 store 有任何依赖,并且可以充当展示组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM