I am currently developing a series of CRUD components with Angular 2. All the examples I have found online so far have the Http
service inside the components. In other words, the component that creates a resource (lets call it ResourceCreate
) includes the code that uses the Http
class to create the resource on the remote server. Similarly, the component that is displaying a list with all the resources (lets call it ResourceList
) includes the code that uses the Http
class to fetch a list of resources from the server.
This works just fine unless you want, for example, to use the ResourceList
to render a list of resources that are not located on the server yet but they were generated temporary on the client. An other example would be to use the ResourceCreate
just to type resource information but save it locally and not on a server. In the above two cases, having the Http
service in the components is redundant.
So my idea for these components is the following:
ResourceCreate
, ResourceList
).Http
to submit or receive data, have the parent component pass data to Input()s
or listen for Output()
events of the CRUD sub-components. For example, have the parent component do an Http
request to fetch a resource list and then pass that list to the ResourcetList
component. Another example could be to have the ResourceCreate
component emit a submit
event along with the resource description. This event will be caught by the parent component and then the parent component will submit this to the server.By using the approach the CRUD components know nothing about the resource storage. So, if our resources are located locally, or in a file, the only thing we have to change is the parent component and not the CRUD components themselves.This makes the CRUD components more reusable.
I am trying to understand if there is a drawback in this approach. Why none of the CRUD examples I find on the internet don't use this approach, but rather they embed the Http
service inside the CRUD components? Any ideas?
Thanks in advance.
According to angular.io
A Component controls a patch of screen real estate that we could call a view
This means that ideally, we should create components that have views associated to them. The drawback of your approach is that the component you create will go through the complete component life cycle, which will be an overhead in your case, since you are not having any view associated to it.
Also, you cannot create your architecture without putting elements in the view. The communication parts of any component should be independent of the view.
A better alternative would be to create a service which wraps the storage mechanism (http/ locally) and inject it into the CRUD components. This allows isolation of CRUD components from the data storage.