Showing posts with label Services. Show all posts
Showing posts with label Services. Show all posts

Sunday, October 7, 2018

Service example in Angular 6

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.