Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught (in promise): Error: Invalid CanActivate guard

Tags:

angular7

Im newbee for angular 7 and now trying to implement CanActive, but im getting error :

enter image description here

Can anyone guide me to overcome this. My code samples are as follows :

auth.guard.ts :

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth-service.service';
import {Router} from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private auth: AuthService,
              private myRoute: Router){
  }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if (this.auth.isLoggednIn()){
      return true;
    } else {
      this.myRoute.navigate(["login"]);
      return false;
    }
  }
}
like image 357
learningBird Avatar asked Mar 05 '19 05:03

learningBird


People also ask

Can you activate Auth guard?

The canActivate guard checks if the user can visit the specific route or we have to prevent access to that specific route. We use the this guard when we have to check some condition and based on that users have the access to reach that specific route or not, before activating the component or showing it to the user.

What is canActivate in Angular?

CanActivatelinkInterface that a class can implement to be a guard deciding if a route can be activated. If all guards return true , navigation continues. If any guard returns false , navigation is cancelled.

What happens when canActivate returns false?

canActivate, canActivateChild will result in NavigationCancel event if 'false'/reject() happens in the Guard. Additionally the URL is reset to the base path before the navigation attempt (as though to leave the user on the page they navigated from).

What is Auth guard?

AuthGuard is used to protect the routes from unauthorized access. So here we are creating an AuthGuard in angular that will protect our routes from unauthorized access. Example: We can create an AuthGuard by running simple command using CLI. ng g guard services/auth.


2 Answers

Using a promise in an if condition is always a bad idea, since it does not get resolved. You could return the promise itself, using resolve to pass the resulting boolean further down the line:

canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Promise<boolean> | boolean {
   return new Promise(resolve =>
     this.auth.isLoggednIn()
       .then(status: boolean => {
         if(status === false) {
           this.myRoute.navigate(["login"]);
         }
         resolve(status);
       })
       .catch(() => {
         this.myRoute.navigate(["login"]);
         resolve(false);
         // ... or any other way you want to handle such error case
       })
  }
}
like image 145
Entertain Avatar answered Sep 19 '22 15:09

Entertain


Please try this:

   return this.auth.isLoggednIn() ? true : this.myRoute.navigate(["login"]);

I got the SAME error message when I did the following:

   canDeactivate(component: CreateEmployeeComponent): boolean {
        if(component.createEmployeeForm.dirty) {
           return confirm('Are you sure you want to discard your changes?');
        }
        return true;
   }

So I solved the problem in the following way:

    canDeactivate(component: CreateEmployeeComponent): boolean {
         return component.createEmployeeForm.dirty 
                ? confirm('Are you sure you want to discard your changes?') 
                : true;    
    }

I'm not sure it works for you, but you can at least give it a try.

like image 29
William Hou Avatar answered Sep 19 '22 15:09

William Hou