Angular Service & Dependency Injection #
Services: #
Services in Angular serve as repositories for reusable code, facilitating storage and accessibility throughout the application.
- Example:
filename.service.ts
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class LoggingService { logStatusChange(status: string) { console.log("Status: ", status); } }
- The optimal approach to using a service is through dependency injection.
Angular Dependency Injection: #
In Angular, Dependency Injection is about components and services getting what they need from a central source, making things modular and easy to manage.
Usage in Component: #
import { LoggingService } from 'path/to/logging.service';
export class YourComponent {
constructor(private log: LoggingService) {}
ngOnInit() {
this.log.logStatusChange('Some Text Status');
}
}

Example: Making it Injectable in a Component: #
@Component({
// Other component configurations
providers: [LoggingService],
})
- Add your service into the
providers
array of@Component
or your module, and just like that,you can used it wherever needed inside the module scope.