Using Services in Angular
This document outlines the three fundamental steps for implementing and using a service in an Angular application.
Step 1: Create the Service
Services are used to share data and business logic across multiple components.
- Generate a service using the Angular CLI:
ng generate service <service-name>(orng g s <service-name>). - Define methods within the service class to provide data or perform actions. For example, a
getEmployees()method can return an array of employee data.
import { Injectable } from '@angular/core';
@Injectable()
export class EmployeeService {
getEmployees() {
return [
{ "id": 1, "name": "Andrew", "age": 30 },
{ "id": 2, "name": "Brandon", "age": 25 },
];
}
}
Note
Initially, it's good practice for components that will use the service to initialize their local data properties (e.g.,
employees) to an empty array.
Step 2: Register the Service
A service must be registered with Angular's dependency injector to be available for use.
- Registration Scopes: Where you register a service determines its availability.
- Component Level: The service is available only to that component and its children.
- Module Level: The service is available to all components declared within that module. This is the most common and recommended approach for feature-wide services.
- How to Register: Add the service class to the
providersarray in the appropriate NgModule decorator (@NgModule).
import { EmployeeService } from './employee.service';
// ... in @NgModule metadata
providers: [EmployeeService],
Important
Angular has a hierarchical dependency injection system. Registering a service at the module level makes a single instance of that service available to all components in that module, promoting efficiency and state sharing.
Step 3: Inject the Service into a Component
Once registered, components can declare the service as a dependency to use it.
- Declare Dependency: Use the component's
constructorto inject an instance of the service.- TypeScript's shorthand syntax (
private _employeeService: EmployeeService) is a concise way to declare it as a private property.
- TypeScript's shorthand syntax (
- Use the Service: Call the service's methods to fetch data or execute logic, typically within a lifecycle hook like
ngOnInit.
import { EmployeeService } from './employee.service';
// ... in component class
export class EmployeeListComponent implements OnInit {
public employees = [];
constructor(private _employeeService: EmployeeService) { }
ngOnInit() {
this.employees = this._employeeService.getEmployees();
}
}
Tip
The
ngOnInitlifecycle hook is the ideal place for initial data fetching because it runs after the component has been initialized and its inputs are set.
Understanding the @Injectable Decorator
- The
@Injectable()decorator on a service class tells Angular that this class can have its own dependencies injected into it. - While not strictly necessary if the service has no dependencies, it is a best practice to add it to all services from the start, as the Angular CLI does automatically.
- Why don't components need
@Injectable()? Components already have the@Component()decorator, which informs Angular that they are part of the dependency injection system.
