</>
Skip to content
Angular lessons (34/43)

Angular — Authentication

Auth Service

@Injectable({ providedIn: 'root' })
export class AuthService {
  private http = inject(HttpClient);
  private router = inject(Router);
  
  login(credentials: {email: string, password: string}) {
    return this.http.post<{token: string}>('/api/auth/login', credentials)
      .pipe(
        tap(response => {
          localStorage.setItem('token', response.token);
        })
      );
  }
  
  logout() {
    localStorage.removeItem('token');
    this.router.navigate(['/login']);
  }
  
  isLoggedIn(): boolean {
    return !!localStorage.getItem('token');
  }
  
  getToken(): string | null {
    return localStorage.getItem('token');
  }
}

Login Component

@Component({
  template: `
    <form [formGroup]="form" (ngSubmit)="onSubmit()">
      <input formControlName="email" type="email">
      <input formControlName="password" type="password">
      <button type="submit" [disabled]="loading">Login</button>
    </form>
  `
})
export class LoginComponent {
  form = new FormGroup({
    email: new FormControl(''),
    password: new FormControl('')
  });
  loading = false;
  
  constructor(private authService: AuthService, private router: Router) {}
  
  onSubmit() {
    this.loading = true;
    this.authService.login(this.form.value).subscribe({
      next: () => this.router.navigate(['/dashboard']),
      error: (err) => {
        this.loading = false;
        console.error(err);
      }
    });
  }
}

Mini Practice

  1. Create an auth service
  2. Implement login
  3. Store JWT token
  4. Add logout functionality

Up Next

Continue with Testing — testing Angular applications.

Related Topics

Frequently Asked Questions about Authentication

What is Authentication in Angular?

Authentication is a fundamental concept in Angular. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Authentication?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Authentication.

Why is Authentication important in Angular?

Authentication is essential for Angular development. Understanding this concept will help you write better code and solve real-world problems more effectively.