Skip to main content

What are Services

In Angular, we often need to share data or functionalities between components. This is where services come into play. A service in Angular is simply a TypeScript class that encapsulates a specific functionality or set of functionalities. Services provide a method for us to keep our components lean and efficient by delegating tasks that aren't related to the user interface.

Creating a Service

Creating a service in Angular is quite straightforward. You can do this by using the Angular CLI command ng generate service, followed by the name of the service. For example:

ng generate service data

This command will generate a service named data. The service will be created in its own file, data.service.ts.

Service Class

The service class is where you define the methods and properties that your service will have. Here's an example of what a service class might look like:

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

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

private data: string[] = ['Item1', 'Item2', 'Item3'];

constructor() { }

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

}

In this example, the DataService service has a single method, getData(), which fetches an array of strings. The @Injectable decorator tells Angular that this class can be used with the dependency injector.

Using a Service

To use a service, you need to inject it into the component that needs it. This is done through the component's constructor. Here's an example:

import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {

data: string[];

constructor(private dataService: DataService) {
this.data = this.dataService.getData();
}

}

In the example above, the DataService is injected into the AppComponent through its constructor. The service is then used to fetch data, which is stored in the data property of the component.

Conclusion

In summary, services in Angular are a powerful tool for sharing data and functionalities between components. They help to keep components lean and focused on presenting data to the user, while offloading data fetching and manipulation to the service. Services are created using the Angular CLI and are provided to components through dependency injection.