Services in Angular are classes which perform
a specific / unit of work. Services with a well-defined purpose and help in
modularizing the application design.
Components deal with the UI of the application, hence they delegate data specific operations like fetching data from server, validating data etc to Services. Since services are outside the component, they can be re-used by injecting into the required components, thereby enabling re-usability of shared service code.
To create a new service we need to use the ng generate cli command
ng generate service
In the following example we shall create a very simple service hello.service, which has a function getMessage(), the function just returns a string message. We shall use this service in a component and display the message returned by the service in the component UI.
Components deal with the UI of the application, hence they delegate data specific operations like fetching data from server, validating data etc to Services. Since services are outside the component, they can be re-used by injecting into the required components, thereby enabling re-usability of shared service code.
To create a new service we need to use the ng generate cli command
ng generate service
In the following example we shall create a very simple service hello.service, which has a function getMessage(), the function just returns a string message. We shall use this service in a component and display the message returned by the service in the component UI.