Angular Services
Building Reusable Logic
Angular Services: Building Reusable Logic
Services in Angular
In Angular, services are a powerful mechanism for organizing and sharing reusable logic across your application. They encapsulate specific functionalities, enabling cleaner code, easier maintenance, and improved testability.
Creating a Service
To create a service, use the Angular CLI command:
ng generate service my-service
This will generate a new service file (e.g., `my-service.service.ts`).
Providing a Service
Services need to be made available to other components. This is done by registering them in the application's root module or a specific feature module:
import { MyService } from './my-service.service';
@NgModule({
// ...
providers: [MyService]
})
export class AppModule { }</code
>
Using a Service
Inject services into components using the constructor:
import { MyService } from './my-service.service';
@Component({ ... })
export class MyComponent {
constructor(private myService: MyService) { }
}
Now you can access the service's methods and properties within the component.
Do You Know?
Services can also be injected into other services, creating a hierarchy of functionalities.
Service Lifecycle Hooks
Services have lifecycle hooks that are triggered at specific points in their lifecycle:
constructor()
: Called when the service is instantiated.ngOnInit()
: Called after the service is initialized.ngOnDestroy()
: Called before the service is destroyed.
Important Note
Use ngOnDestroy()
to clean up resources or unsubscribe from observables to prevent memory leaks.
Types of Services
Data Services
Data services handle fetching and managing data. They can interact with APIs, local storage, or other data sources.
Utility Services
Utility services provide reusable functions and methods that can be applied to various parts of the application. Examples include validation, string manipulation, or date formatting services.
Communication Services
Communication services enable components to interact with each other. They can facilitate data exchange, event broadcasting, or messaging between different parts of the application.
Avoid This
Do not put complex business logic or UI-related code inside services. Keep them focused on providing reusable functionalities.
Summary
- Services in Angular promote code reusability and maintainability.
- Create services using the CLI command
ng generate service
. - Provide services in modules to make them available to components.
- Inject services into components using the constructor.
- Services have lifecycle hooks for handling initialization and destruction.
- Use different types of services for data access, utility functions, and communication.