Angular services are essential for sharing code across multiple components. They act as singletons, meaning that though your app might instantiate multiple services, each individual service is instantiated only once. This allows you to share functions and properties across your app from a single instance. Services are ideal for tasks like calling APIs or storing session data, enabling you to share information between components without repeatedly hitting a web service.
This tutorial demonstrates a service implementation in modern Angular (as of version 17), utilizing the Angular CLI to create a basic example. Let's dive in!
Key Takeaways
- Angular services function as singletons, facilitating shared functionality and state.
- Services are crucial for dependency management and promoting code reuse.
- The @Injectable decorator is key to enabling dependency injection in services.
Angular Service Example
Start by creating a new Angular project using the CLI:
ng new angularServiceExample
This sets up a project named angularServiceExample. Navigate to the root directory and generate a new service:
ng generate service session
This creates the following:
session.service.tsin thesrc/appdirectory.session.service.spec.tsfor testing.
Unlike other commands, ng generate service does not automatically register the service in your root module. You need to manually add it to app.module.ts as a provider:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { SessionService } from './session.service';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [SessionService],
bootstrap: [AppComponent]
})
export class AppModule { }
This inclusion makes SessionService available throughout your application.
Adding Properties to the SessionService
Update your session.service.ts file with:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class SessionService {
userName = "Sam";
constructor() { }
}
@Injectable Decorator
The @Injectable decorator allows Angular to inject the dependencies needed by your service. Even if your service doesn't currently have dependencies, always include @Injectable to support future changes and maintain consistency.
Using the Service in a Component
To use SessionService in a component, edit app.component.ts:
import { Component } from '@angular/core';
import { SessionService } from './session.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
currentUser: string;
constructor(private sessionService: SessionService) {
this.currentUser = this.sessionService.userName;
}
}
Here, the service is injected into the AppComponent via the constructor, demonstrating Angular's dependency injection.
In app.component.html, display the retrieved property:
Hello {{ currentUser }}
Launch your app with ng serve, open localhost:4200, and see "Hello Sam".
Conclusion
This example illustrates how to implement an Angular service. Use the @Injectable decorator to ensure dependency injection capabilities. Angular services optimize shared logic and data management across components, reinforcing modular application architecture.
FAQ
Why not automatically include services in the root module?
Having developers manually add services ensures intentional usage and prevents them from becoming accidentally bloated or misconfigured.
Is @Injectable always required?
While not strictly necessary if a service has no dependencies, it's a best practice to include it for future-proofing and code uniformity.
Can services have their own dependencies?
Yes, services can depend on other services or components by accepting these as constructor parameters, allowing complex functionality to be built from smaller pieces.
What's the benefit of registering services with providedIn: 'root'?
Using providedIn: 'root' makes your service a singleton and automatically included in the app's root injector, simplifying module configuration.
