Service is a piece of reusable code with a focused purpose. A code that you will use in many components across your application
Our components need to access the data. You can write data access code in each component, but that is very inefficient and breaks the rule of single responsibility. The Component must focus on presenting data to the user. The task of getting data from the back-end server must be delegated to some other class. We call such a class a Service class. Because it provides the service of providing data to every component that needs it.
What Angular Services are used for
Features that are independent of components such a logging services
Share logic or data across components
Encapsulate external interactions like data access
Advantages of Angular Service
Services are easier to test.
They are easier to Debug.
We can reuse the service at many places.
How to create a Service in Angular?
An Angular service is simply a Javascript function. All we need to do is to create a class and add methods & properties. We can then create an instance of this class in our component and call its methods.
Step 1
Create a new file under the folder src/app and call it User.ts
Next, let us build an Angular Service, which returns the list of users.
Create a new file under the folder src/app and call it user.service.ts with the help of Angular CLI. Type the below mentioned command and this command will generate the service for us.
ng g s service/user
import { Injectable } from '@angular/core';
import { User } from '../User';
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor() {}
}
Step 3
Now add the below mentioned methods to perform CRUD operation
Join the conversation! Your thoughts help the community grow.