Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: Best Practice for Data Layer

I am new to Angular2 and am learning by doing. Right now I have succeeded in building one of multiple view with a parent component, couple of child components and database service. Now I am about to move to implementation of other views with their respective parent-child components.

The application should use the same dataset which can be added/updated/deleted within other components, so I am looking into having a separate data layer, which can be directly queried by all of the components of the application. Even more – I need the same instance of the service, so that the intermediate data is available everywhere and, well, to 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, when I have direct access to variables of the same instance of the data layer all over the application, what is the best way to deal with variables within components?

a) Should I work with local component variables, which are the copies of the same data layer variables (thus loading, getting and setting them explicitly), like

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 layer variables, iterating over them, getting and setting them from within a component?

updateLocation(id) {
   this.datalayer.selectedLocation = id;
}

getSelectedLocation() {
   return this.datalayer.selectedLocation;
}

or maybe there is an option c?

like image 384
pop Avatar asked Dec 15 '16 09:12

pop


1 Answers

I presume you want a service, that is available to all components that the purpose is to interact with data.

You also want a service that is a singleton.

The solution is to create the service and provide it on the app level.

See more:

How can I create a singleton service in Angular 2?

like image 177
Joel Almeida Avatar answered Sep 20 '22 17:09

Joel Almeida