How to create and use Services in Angular?

In Angular, a service is typically a class that contains business logic, models, data, and functions that can be invoked from any component of an Angular application.

Angular separates components from services to increase modularity and reusability. By separating business processing logic from view-related functions of a component, the component classes becomes simple and efficient.

Why Services?

Components should never directly fetch or save data. They should concentrate on data presentation and delegate data access to a service.

Services make sharing of information among classes that do not know each other easier.

By removing data access from components, we can change the implementation at any time without having to touch any components. They have no idea how the service operates.

Creating a Service

To create a service in Angular, you can use the Angular CLI command as shown in the example below:

ng generate service User

The above command will generate a skeleton UserService class in src/app/user.service.ts as follows:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class UserService {

  constructor() { }
}

The code in the above file starts with importing of Angular Injectable and annotating the class with @Injectable() decorator. This @Injectable() decorator indicates that the class is part of the dependency injection mechanism.

The @Injectable() decorator, just like the @Component decorator, accepts a metadata object for the service classes. The providerIn property of the metadata object, creates a provider for the service. The providerIn:'root' property specifies that Angular must provide this service in the root injector. The UserService class is now able to provide an injectable service and it can also have its own injected dependencies.

The constructor() is required to inject dependencies into the service.

The export keyword makes this class visible to other components and services.

How to use Services in Angular?

A service can get data from any source, including a local storage, a webservice, or a mock data source.

A service can be injected in many components and anywhere as necessary in the application.

To use a service in a component, the service should be injected into the Component constructor using Angular dependency injection rather than creating the service using the new keyword.

When we provide a service at the root level, Angular creates a single, shared instance of the service and injects it into any class that requests it. By registering the provider in the @Injectable metadata, Angular also optimizes an application by removing the service if it isn't used or not needed.