jeudi 25 août 2016

What component should fetch data in angular 1.5, 2, react? root or child?

I'm working at new project with angular 1.5 (starting component path of building), but question is not about angular, it's about design pattern.

Lets say i have complex website with this main page:

<header></header>
<sidebar-left></sidebar-left>
<sidebar-right></sidebar-rigth>
<mainSection>
  <news></news>
  <movie-list></movie-list>
  <random-quotes></random-quotes>
</mainSection>
<footer></footer>

News, movie list and quotes blocks displaying data from server. Each from their own method/api. So WHO is responsible for fetching data? Should main component fetch data and pass it to children? Or news, movieList and randomQuotes components should fetch data by itself?

1) Main component fetching data map it to scope and pass to children

<mainSection>
  <news items="$ctrl.news"></news>
  <movie-list items="$ctrl.movies"></movie-list>
  <random-quotes items="$ctrl.quotes"></random-quotes>
</mainSection>

VS

2) Every child component should fetch data

class MovieListController {
  constructor(MovieService) {
    this.movieService = MovieService;
  }
  $onInit() {
    this.movies = [];
    this.movieService.getAll().then(response => this.movies = response);
  }
}

export const movieList = {
  template: '<movie-item ng-repeat="movie in $ctrl.movies"></movie-item>',
  controller: MovieListController,
};

Aucun commentaire:

Enregistrer un commentaire