Injecting services lets components use shared features like data or functions without repeating code. It helps keep your app organized and easy to update.
0
0
Injecting services into components in Angular
Introduction
When you want to share data or logic between different parts of your app.
When you need to get data from a server and show it in a component.
When you want to keep your component code simple by moving complex tasks to a service.
When you want to reuse the same functionality in many components.
When you want to test components easily by swapping services.
Syntax
Angular
import { Component, inject } from '@angular/core'; import { MyService } from './my-service'; @Component({ selector: 'app-example', templateUrl: './example.component.html', standalone: true }) export class ExampleComponent { private myService = inject(MyService); constructor() { // You can now use this.myService inside the component } }
Use the inject() function inside the component class to get the service instance.
Make sure the service is provided in the app or component scope so Angular can create it.
Examples
This example injects a LoggerService to log a message when the component is created.
Angular
import { Component, inject } from '@angular/core'; import { LoggerService } from './logger.service'; @Component({ selector: 'app-log', template: '<p>Check console for logs</p>', standalone: true }) export class LogComponent { private logger = inject(LoggerService); constructor() { this.logger.log('LogComponent created'); } }
This example injects a DataService to get some data and show it in the template.
Angular
import { Component, inject } from '@angular/core'; import { DataService } from './data.service'; @Component({ selector: 'app-data', template: '<p>Data: {{ data }}</p>', standalone: true }) export class DataComponent { private dataService = inject(DataService); data = ''; constructor() { this.data = this.dataService.getData(); } }
Sample Program
This component uses the GreetingService to get a greeting message and shows it in a paragraph.
Angular
import { Component, inject } from '@angular/core'; // Simple service that returns a greeting export class GreetingService { getGreeting() { return 'Hello from the service!'; } } @Component({ selector: 'app-greet', template: `<p>{{ greeting }}</p>`, standalone: true, providers: [GreetingService] }) export class GreetComponent { private greetingService = inject(GreetingService); greeting = ''; constructor() { this.greeting = this.greetingService.getGreeting(); } }
OutputSuccess
Important Notes
Always add the service to the providers array if it is not provided globally.
Using inject() is the modern way in Angular 16+ for standalone components.
Services help keep your components clean and focused on the UI.
Summary
Injecting services lets components use shared code easily.
Use the inject() function inside the component class to get the service.
Remember to provide the service so Angular can create it.