I'm trying to use an HTTP request inside guard, but always getting errors. when I remove the HTTP request and use an if condition, it's work.
isAdmin.guard.ts
import { Injectable } from '@angular/core';
import { Router ,CanActivate } from '@angular/router';
import { AuthService } from '../services/auth.service';
@injectable()
export class IsAdmin implements CanActivate {
constructor(
private auth:AuthService,
private router:Router
){}
canActivate(){
//get user data
this.auth.getUserData().subscribe((data)=>{
if(data.isAdmin){
return true;
}else{
this.auth.loggedIn();
this.router.navigate(['/login']);
}
})
}
}
Photo from editor
CanActivate must return a Observable<boolean> | Promise<boolean> | boolean
as you can see in this link.
interface CanActivate {
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean
}
In your case, you should only return this.auth.getUserData()
. But such function doesn't return an Observable<boolean>
, instead, it returns Observable<data>
. So you should map it to return a Observable<boolean>
:
canActivate(): Observable<boolean> {
//get user data
return this.auth.getUserData().map((data)=>{
if(data.isAdmin){
return true;
}else{
this.auth.loggedIn();
this.router.navigate(['/login']
return false;
}
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With