Components are designed primarily for data binding and handling view-related logic.
If you have complex business logic, or need to fetch data from an API, that code does not belong in a component.
Instead, you should extract that logic into reusable classes called Services.
A Service is simply a TypeScript class equipped with a special @Injectable decorator.
This decorator allows Angular to inject the service into any component that requests it.
You can instantly generate a new service using the CLI command: ng generate service my-service.
import { Injectable } from '@angular/core';
// This setting makes the service a Singleton available everywhere!
@Injectable({
providedIn: 'root',
})
export class LoggerService {
logMessage(msg: string) {
console.log("Logger Service Says: " + msg);
}
}
Dependency Injection is a design pattern deeply baked into Angular's core architecture.
Instead of a component manually instantiating a service (e.g., let service = new LoggerService()), it simply asks Angular for it.
Angular looks at the request, creates the service instance in the background, and seamlessly "injects" it into the component.
To inject a service, you declare it as a parameter inside the component's constructor method.
By marking the parameter as private or public, TypeScript automatically creates a class property for it.
import { Component } from '@angular/core';
import { LoggerService } from './logger.service';
@Component({
selector: 'app-home',
template: '<button (click)="testLog()">Test Service</button>'
})
export class HomeComponent {
// Angular automatically injects the LoggerService right here!
constructor(private logger: LoggerService) {}
testLog() {
this.logger.logMessage("The button was clicked!");
}
}
Which decorator is required to make a TypeScript class function as an injectable Angular Service?
Where must you declare the service parameter in order for Angular to automatically inject it into your component?