Service layer in Angular

| By Webner

Angular service is very useful to organize business logic or data in the different components of an application. The methods written in the service file can be invoked from different typescript files of a component. The controller is responsible for binding data with view and model.

How to use service in the typescript file ( Controller )

An angular application has a number of components. To fetch data for the entire application an ajax call is initiated from the controller. The same code will be written to make ajax calls. In such cases, service is very helpful to reduce code. Fetching data within the controller is not the best way. So, to use service in the component, import that service in the component and inject that service into the controller.

Command to create service-

ng generate service “Service Name”

Use article service in the typescript file (app.component.ts)-

Angular 1

Article service file (article.service.ts)-

Angular 2

View file (app.component.html)-



Leave a Reply

Your email address will not be published. Required fields are marked *