Skip to content

Commit bb4fee1

Browse files
committed
feat: enhance auth-guard with error handling and cleanup logic
1 parent 737fdc2 commit bb4fee1

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

src/app/guards/auth-guard.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,26 @@
11
import { CanMatchFn, Router } from '@angular/router'
2-
import { inject } from '@angular/core'
2+
import { DestroyRef, inject } from '@angular/core'
33
import { AuthService } from '../services/auth-service'
44
import { map } from 'rxjs/operators'
55
import { UserService } from '../services/user-service'
6+
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'
7+
import { catchError, of } from 'rxjs'
8+
import { HttpErrorResponse } from '@angular/common/http'
69

710
export const authGuard: CanMatchFn = (route, segments) => {
811
const savedUserId = localStorage.getItem('user')
912

1013
const router = inject(Router)
1114
const authService = inject(AuthService)
1215
const userService = inject(UserService)
16+
const destroyRef = inject(DestroyRef)
1317

1418
if (savedUserId) {
1519
return userService.getUser().pipe(
20+
takeUntilDestroyed(destroyRef),
21+
catchError((error: HttpErrorResponse) => {
22+
return of(null)
23+
}),
1624
map((user) => {
1725
if (user) {
1826
authService.updateAuth(user)

0 commit comments

Comments
 (0)