I am using angular 2 for my personal project. So here's the simplified scenario with some sudo-code.
app
 |- main.ts            /* bootstrap the app */
 |- app.component.ts   /* basically with a template: `<nav></nav>
 |                                                    <router-outlet></router-outlet>`.
 |                        And also have providers: [CatService] */
 |- nav.component.ts   /* a navigation bar where each cat's name is an option. 
 |                        ngOnInit(){ this._catService.getCats().then(assignCats) } */
 |
 |- cat.components.ts  /* show the cat's detail selected from the nav component 
                          ngOnInit(){ this._catService.getCat().then(assignCat); } */
 |
 |- cat.service.ts     /* getCats() method to send query to a database for all the cats */
Ok. I hope this doesn't look too complicated.
The only problem is, I am calling the this._catService.getCats() which sends query to the database in both nav.component and cat.component. But there actually has no point sending the query twice as I already know the data is not going to change often. I can only thought of two ways of handling this now:
- Cache the result of the database call in - this._catService.getCats()so that in the second call, it can return the cached value instead of sending a second query.
- Do the query at - app.componentthen pass the result to- navand- catas- @input. But then this means later if I have a new component I have to pass the result to it too? then end up the template of- app.componentmight become something like:- <nav [cats]="queriedCats"></nav>,- <cat [cats]="queriedCats"></cat>,- <somecomponent [cats]="queriedCats"></somecomponent>... which looks really bad to me.
What do you think? Which way is the prefered way to do it?
 
     
    