This tutorial demonstrates how to create and use services in an Angular application built with standalone components. We’ll integrate a service for managing user authentication and apply dependency injection to use the service across multiple components and guards.
1. What Are Services?
Services in Angular provide reusable business logic or data management across the application. They’re often used for:
- Shared State: Managing shared data or state (e.g., user authentication).
- API Calls: Interacting with external APIs.
- Utilities: Reusable methods (e.g., logging).
2. Create a Service
Generate a service using the Angular CLI:
ng generate service auth
This creates auth.service.ts
. Update it as follows:
src/app/auth.service.ts
:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root', // Automatically provides this service at the root level
})
export class AuthService {
private isAuthenticated = false;
login(): void {
this.isAuthenticated = true;
}
logout(): void {
this.isAuthenticated = false;
}
isLoggedIn(): boolean {
return this.isAuthenticated;
}
}
This service manages a mock authentication state with methods to log in, log out, and check the authentication status.
3. Inject the Service into the Guard
Update the AuthGuard
to use AuthService
for authentication logic.
src/app/auth.guard.ts
:
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root',
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(): boolean {
if (this.authService.isLoggedIn()) {
return true;
} else {
alert('Access denied. Please log in.');
this.router.navigate(['/']);
return false;
}
}
}
4. Use the Service in AppComponent
Update AppComponent
to use the AuthService
for login and logout functionality.
src/app/app.component.ts
:
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { AuthService } from './auth.service';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet],
template: `
<nav>
<a routerLink="/" routerLinkActive="active">Home</a>
<a routerLink="/about" routerLinkActive="active">About</a>
<a routerLink="/contact" routerLinkActive="active">Contact</a>
</nav>
<button (click)="login()">Login</button>
<button (click)="logout()">Logout</button>
<router-outlet></router-outlet>
`,
styles: [`
nav {
display: flex;
gap: 1rem;
margin-bottom: 1rem;
}
.active {
font-weight: bold;
color: blue;
}
button {
margin-right: 10px;
}
`],
})
export class AppComponent {
constructor(private authService: AuthService) {}
login() {
this.authService.login();
alert('You are now logged in!');
}
logout() {
this.authService.logout();
alert('You are now logged out!');
}
}
5. Inject the Service into Components
If other components need authentication-related logic, they can also inject the AuthService
. For example:
src/app/contact/contact.component.ts
:
import { Component } from '@angular/core';
import { AuthService } from '../auth.service';
@Component({
selector: 'app-contact',
standalone: true,
template: `
<h1>Contact Us</h1>
<p *ngIf="authService.isLoggedIn(); else notLoggedIn">
Welcome, authenticated user! Feel free to contact us.
</p>
<ng-template #notLoggedIn>
<p>Please log in to see contact details.</p>
</ng-template>
`,
styles: [`h1 { color: orange; }`],
})
export class ContactComponent {
constructor(public authService: AuthService) {}
}
Key Concepts Recap:
- Services: Provide shared business logic, like authentication.
- Dependency Injection: Services are injected into components and guards to access their functionality.
- Reusability: Services can be shared across multiple parts of the application, maintaining consistent logic.
This approach ensures separation of concerns: the AuthService handles authentication logic, and components or guards use it without duplicating code.
Pingback: What Is Angular - Tech Mentor