I am new to Angular2 and I am learning. Now I have managed to create one of several views with a parent component, two child components and a database service. Now I'm going to move on to implement other views with their respective parent-child components.
An application should use the same dataset that can be added / updated / deleted in other components, so I look at a separate data layer that can be directly requested by all application components. Even more - I need the same instance of the service, so that the intermediate data is available everywhere and, in addition, also avoid unnecessary trips to the database. What is the best way to define and use such a class in Angular2?
Update Q:
So now that I have direct access to the variables of the same instance of the data layer throughout the application, what is the best way to deal with variables inside the components?
a) Should I work with local variables of the component, which are copies of the same data-level variables (thus loading, receiving and setting them explicitly), for example
this.locations = this.datalayer.locations;
this.selectedLocation;
updateLocation(id) {
this.selectedLocation = id;
this.datalayer.setSelectedLocation(id);
}
getSelectedLocation() {
return this.selectedLocation;
}
or b) should I work exclusively with data-level variables, iterating over them, getting and setting them from within the component?
updateLocation(id) {
this.datalayer.selectedLocation = id;
}
getSelectedLocation() {
return this.datalayer.selectedLocation;
}
or maybe there is option c?
source
share