What is a service in Angular and when is it used?
In Angular, a service is a reusable piece of code that encapsulates a specific functionality or data and provides it to multiple parts of the application through dependency injection. Services are used to encapsulate business logic, data access, and other non-UI related functionality, and make it available to components throughout the application.
A common use case for services is to centralize data access logic. For example, you can create a service that fetches data from a remote server and makes it available to your components. This way, your components don’t need to know about the details of fetching the data and can simply use the data provided by the service.
Another use case for services is to share data and functionality between components. For example, you can create a service that keeps track of the current user’s information and makes it available to any component that needs it.
To create a service in Angular, you define a class with the desired functionality and then register it with the Angular injector. This makes it possible to use the service in any component by injecting it into the component’s constructor.
Here is an example of a simple service in Angular:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class UserService {
private user: User;
constructor() { }
setUser(user: User) {
this.user = user;
}
getUser(): User {
return this.user;
}
}
In this example, the UserService
class is decorated with the @Injectable
decorator, which makes it possible to inject the service into other components. The setUser
method is used to set the current user, and the getUser
method is used to retrieve the current user. The providedIn
property of the @Injectable
decorator is set to 'root'
, which means that the service is available globally throughout the application and does not need to be imported in each individual component.