Reputation: 3451
When I start my angular app, on init, I hit and endpoint which returns me data for a particular route, so when I go to the home page, I query the database for the home page data and return that. Likewise, when I go to the contact route, I query the database for the contact data and return that. This requires a call to the database every time I navigate to a route. So my question is sort of two parts.
Thanks
Upvotes: 1
Views: 1892
Reputation: 847
You should definitely use ngrx/store for this.
This strategy uses redux pattern for storing persistent data (application state) in your application in an immutable single source of truth, making it accessible in every single component of your application.
Your main store will be modified only by actions dispatched by your components, so all business logic won't be component-dependant, being possible to reuse functions (actions in this case) between components without rewriting them every single time.
In each component you will be able to select a slice of this main store and subscribe to it's changes, as this function returns an observable, so your components will always be up to date with your main store (state).
Take a look at these tutorials, they explain this concept really well: https://malcoded.com/posts/angular-ngrx-guide https://medium.com/stratajet-tech/a-beginners-guide-to-ngrx-store-bc2184d6d7f0
It's a little tricky at the beggining but trust me, as soon as you understand it, you will forget Angular services, event emitters, @input and @output to create component interaction and data reusability, and you will see how amazing it is to move your business logic away from your components and be able to reuse it from anywhere.
It really makes things super simple to use this concept.
Upvotes: 0
Reputation: 13910
The recommended way of passing data between components is to use a service. Since services in Angular 2 are singletons *, when your other components request it, it will receive the same instance with your data. This is how you would achieve what you are looking for
Service
export class DataService {
public dataOne: Data;
public dataTwo: Data;
}
BaseComponent
...
constructor(private dataService: DataService) { }
ngOnInit() {
// Make your calls and populate these variables with the corresponding data
this.dataService.dataOne = {};
this.dataService.dataTwo = {};
}
...
ConsumerComponent
...
constructor(private dataService: DataService) { }
ngOnInit() {
// get the data you added in the base component
var dataOne = this.dataService.dataOne;
}
...
*Angular 2 Services are singletons per provider, so if you add it to providers in the app.module.ts
it will be a true singleton, otherwise, you will get a new instance per provider.
Upvotes: 4