Angular: creating and using services

Angular: creating and using services

When it comes to managing data and business logic in an Angular application, services play a vital role.

Angular is a powerful and flexible front-end framework that facilitates the development of complex and dynamic web applications. When it comes to managing data and business logic in an Angular application, services play a vital role. Services are single classes that provide an efficient way to organize and share code, allowing separation of responsibilities and code reusability.

What is a Service in Angular?

In Angular, a service is a TypeScript class annotated with the @Injectable decorator. This annotation tells Angular that the class can be injected into other components, directives, or services within the application. Services are designed to manage business logic, share data between different components and provide a centralized solution for accessing data or implementing shared functionality.

Create a Service in Angular

To create a service in Angular, you can use the Angular CLI command:


ng generate service serviceName

This command automatically creates a service-name.service.ts file with a service base class. Within this class, you can define the necessary methods, properties, and business logic.

Dependency Injection in Angular

To use a service in a component or another service, you need to inject it. Dependency injection in Angular is a crucial concept that allows you to get an instance of a service inside a component or another service.


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

@Injectable({
   providedIn: 'root',
})
export class NameServiceService {
   // Properties or methods of the service
}

If you want to inject the service into a component, simply declare it in the component constructor:


import { Component } from '@angular/core';
import { NameServiceService } from './name-service.service';

@Component({
   selector: 'app-my-component',
   template: '<p>My component</p>',
   providers: [NameServiceService],
})
export class MyComponent {
   constructor(private nameService: NameServiceService) {}
}

Share Data between Components with Services

One of the main uses of services in Angular is sharing data between components. When two or more components need to access or modify the same data, a service can act as an intermediary.


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

@Injectable({
   providedIn: 'root',
})
export class SharedDataService {
   data: string[] = [];

   addData(value: string) {
     this.data.push(value);
   }

   getData(): string[] {
     return this.data;
   }
}

In this example, the SharedDataService service provides methods for adding and getting data. Interested components can inject this service and use it to share information.

Manage business logic with services

Services in Angular are also ideal for managing complex business logic. This may include API calls, data processing, or any other operation involving data manipulation.


import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
   providedIn: 'root',
})
export class DataService {
   private apiUrl = 'https://api.example.com/data';

   constructor(private http: HttpClient) {}

   fetchData(): Observable {
     return this.http.get(this.apiUrl);
   }
}

In this example, the DataService service uses Angular's HttpClient to make an API call and returns an Observable instance containing the obtained data . This service can be injected into different components that need such data.

Conclusions

Services in Angular play a crucial role in managing data and separating responsibilities within an application. They allow for modular design, improving the maintainability and scalability of the code. Taking full advantage of the services in Angular helps create robust and flexible applications, capable of adapting to the complex needs of the modern world of web development.