Accessing data from components using services
As the Angular application evolves, we keep introducing more components, and these components will be dealing with the core data of the application. As a result, we may end up writing repetitive code to access the data. However, we can avoid writing redundant code by introducing reusable data services. The component that is in need of the data can be injected with the data service, and that can be used to access the data. In this way, we can reuse logic, write less code, and have more separation in designing our components.
We will use the Angular HttpModule
, which is shipped as an npm
package. In order to use HttpModule
in our application, we need to import HttpModule
from @Angular/http
and the HTTP service should be injected into the constructor of the controller or the application service.
Implementing services
An application may share data between components. Consider a movie database application, where a Movies
list or a single Movie
object...