Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular AuthGuard is not working

I am using angular CanActivate Authguard interface to protect my component.

@Injectable()
export class AuthGuard implements CanActivate{

constructor(private router: Router, private authService: AuthenticationService) {}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {

    this.authService.isLoggedIn.take(1).map((isLoggedIn : boolean) => {

        if(!isLoggedIn){
            this.router.navigate(['/login']);
            return false;
        }

        return true;
    })

    this.router.navigate(['/login']);
    return false;
   }
}

i added it to my router configuration like this.

const appRoutes: Routes = [
{path : '',redirectTo : 'login',pathMatch : 'full'},
{ path: 'home', component: HomeComponent,canActivate : [AuthGuard] }
]

I also added it to providers array.

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
providers: [AuthGuard,  
ExpenseService,SellDetailService,AuthenticationService],
styleUrls: ['./app.component.css']
})

But when i run the application its giving following error

StaticInjectorError(AppModule)[AuthGuard]:
StaticInjectorError(Platform: core)[AuthGuard]: NullInjectorError: No provider for AuthGuard!

I think i implemented it courrectly but its not working . what i am doing wrong???

like image 792
user3692033 Avatar asked May 19 '18 06:05

user3692033


People also ask

How does AuthGuard work in Angular?

AuthGuard is used to protect the routes from unauthorized access in angular. How AuthGuard Works? Auth guard provide lifecycle event called canActivate. The canActivate is like a constructor.

Can active guard in Angular?

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.


1 Answers

You should add name of your guards to app.module in providers array Something like this

Providers:[AuthGuard]

like image 105
Stefan Morcodeanu Avatar answered Dec 17 '22 14:12

Stefan Morcodeanu