Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 HTTP request in guard

Tags:

angular

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 enter image description here

enter image description here

like image 887
Mahmoud Niypoo Avatar asked Jan 15 '18 19:01

Mahmoud Niypoo


1 Answers

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;
        }
    })
}
like image 130
Pedro Arantes Avatar answered Sep 27 '22 19:09

Pedro Arantes