Creating Services in Angular
Services in Angular are used to encapsulate reusable logic and data. This tutorial covers the basics of creating services effectively in your Angular applications.
Creating a Service
Create a service using the Angular CLI command ng generate service my
:
$ ng generate service my
This command creates a new service file named my.service.ts
in your project.
Implementing the Service
In the service file, use the @Injectable
decorator to make the service available for dependency injection:
// my.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor() { }
getMessage(): string {
return 'Hello from MyService!';
}
}
Using the Service in a Component
Inject the service into your component's constructor and use it in the component's logic:
// home.component.ts
import { Component, OnInit } from '@angular/core';
import { MyService } from '../my.service';
@Component({
selector: 'app-home',
template: '{{ message }}
',
})
export class HomeComponent implements OnInit {
message: string;
constructor(private myService: MyService) {}
ngOnInit() {
this.message = this.myService.getMessage();
}
}
Providing the Service
Services can be provided at the root level or in specific modules. Using providedIn: 'root'
ensures that the service is a singleton and available application-wide:
// my.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor() { }
getMessage(): string {
return 'Hello from MyService!';
}
}
Key Points
- Create a service using the Angular CLI command
ng generate service my
. - Use the
@Injectable
decorator to make the service available for dependency injection. - Inject the service into your component's constructor to use it in the component's logic.
- Provide the service at the root level using
providedIn: 'root'
to ensure it is a singleton and available application-wide.
Conclusion
Creating services in Angular provides a powerful way to encapsulate reusable logic and data. By understanding and using services effectively, you can create modular and maintainable code. Happy coding!