In Angular, services are classes that are responsible for encapsulating and providing shared functionality, data, or behaviour that can be used across multiple components or throughout an application.
Services help to keep our code modular, reusable, and easier to maintain.
Services help us to keep business logic separate from presentation logic, improving code readability and maintainability.
Services can be injected into components, directives, and other services, making it easy to manage dependencies and promote modularity using Angular's dependency injection.
Here's how we can create and use services in Angular:
We can generate a service using the Angular CLI command:
ng generate service new-service
This will create a service file ("new-service.service.ts") where we can define our service class. you can replace `new-service` name with your service file name.
// new-service.service.ts import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' // This makes the service available throughout the application }) export class NewService { constructor() { } // Example method in the service getData() { return ['data1', 'data2', 'data3']; } }
We can inject the service into a component's constructor and then use its methods or properties within that component.
// new-component.component.ts import { Component, OnInit } from '@angular/core'; import { NewService } from '../new-service.service'; // Import the service @Component({ selector: 'app-new-component', templateUrl: './new-component.component.html', styleUrls: ['./new-component.component.css'] }) export class NewComponent implements OnInit { data: string[]; constructor(private newService: NewService) { } // Inject the service ngOnInit(): void { this.data = this.newService.getData(); // Use the service method } }
We can provide the service at the root level or at the module level.
By using "providedIn: 'root'" in the service decorator, the service will be a singleton and available throughout the application without needing to add it to any module's providers array.
// app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { NewService } from './new-service.service'; // Import the service @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [NewService], // Provide the service here bootstrap: [AppComponent] }) export class AppModule { }
If you want to limit the scope of the service to a specific module and its components, you can provide it in the providers array of that module.
Services are essential for implementing business logic, data fetching, sharing data between components, and handling cross-cutting concerns in Angular applications.