Issue
I want to implement AuthGuard
using CanActivateFn in Angular 16 which should prevent to view some pages for unauthorized users.
isUserLoggedIn
method in UserService
is a get request to the backend which returns a loggedin user or throws UNAUTHORIZED exception.
I want to call isUserLoggedIn
in AuthGuard
and check if it throws UNAUTHORIZED exception then redirect to "/unauth" path otherwise it should return true and do nothing.
The problem: isUserLoggedIn
returns Observable<AuthorizedUser>
and CanActivateFn needs type boolean
. Is there any way to do this without changing the actual GET request in backend ?
@Injectable({providedIn: 'root'})
export class UserService {
isUserLoggedIn(): Observable<AuthorizedUser> {
const headers = new HttpHeaders({'Content-Type': 'application/json'});
return this.apiHandlerService.get<AuthorizedUser>(API_URL, headers);
}
}
import {CanActivateFn, Router,} from '@angular/router';
import {inject} from '@angular/core';
import {catchError, map, of} from "rxjs";
export const AuthGuard: CanActivateFn = (route, state) => {
const authService: UserService = inject(UserService);
const router: Router = inject(Router);
return authService.isUserLoggedIn().pipe(
map(response => {
console.log('Response ', response);
return true;
}),
catchError(error => {
router.navigate(['/unauthorized'])
return of(false);
})
)
}
Solution
I guess you have done it on your own. Do you need anything else?
This is your code:
import {CanActivateFn, Router,} from '@angular/router';
import {inject} from '@angular/core';
import {catchError, map, of} from "rxjs";
export const AuthGuard: CanActivateFn = (route, state) => {
const authService: UserService = inject(UserService);
const router: Router = inject(Router);
return authService.isUserLoggedIn().pipe(
map(response => {
console.log('Response ', response);
return true;
}),
catchError(error => {
router.navigate(['/unauthorized'])
return of(false);
})
)
}
Answered By - NgDaddy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.