简体   繁体   中英

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:

@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.

I believe I should add topPosts: Post[] to my Store and an action '[Posts Page] Load Top Posts'.

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?

    How? And in this case should I change action to '[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.

This way your child component need not have any dependency on the store and can act as presentational components.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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