Angular Services are reusable pieces of code that can be injected.
Defining a Component, Services are made
up of the following:
A TypeScript decorator that declares the class as
an Angular service via @Injectable and allows you to define what part of
the application can access the service via the providedIn property
(which is typically 'root') to allow a service to be accessed anywhere within
the application.
A TypeScript class that defines the desired code that will be accessible when the service is injected.
Let's see an example of a Calculator
service,
import
{Injectable} from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class
CalculatorService {
add(a: number, b: number) {
return a + b;
}
}
How to use an Angular 17 Service?
When you want to use a service in a component, you
need to do the following,
1. Import
the service that you have created.
2. Declare
a class field where the service is injected.
3. Assign
the class field to the result of the call of the Angular built-in function ‘inject’
which creates the service.
See the example of what it looks like,
import {
Component } from '@angular/core';
import {
CalculatorService } from './calculator.service';
@Component({
selector: 'app-receipt’,
template: `<p>The total is {{ totalValue
}}</h1>`,
})
export class
Receipt {
private calculatorService =
inject(CalculatorService);
totalValue = this.calculatorService.add(10, 20);
}
In the above example, the service ‘CalculatorService’
is being used by calling the Angular function ‘inject’ and passing in
the service to it.