Getting "No provider error" when using CanActivate guard
Asked Answered
M

3

8

This is the guard:

// my.guard.ts
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot } from '@angular/router';

Injectable()
export class MyGuard implements CanActivate {
  canActivate(next: ActivatedRouteSnapshot, prev: RouterStateSnapshot) {
    console.log('GUARD:', next, prev);
    return true;
  }
}

This is the router:

import { RouterConfig } from '@angular/router';
import { MyGuard } from './guards/my.guard';
export const AppRoutes : RouterConfig = [
  {
    path: 'home',
    component: HomeComponent,
    canActivate: [MyGuard]
  }
];

When the page loads I get:

EXCEPTION: Error: Uncaught (in promise): No provider for MyGuard!

No tutorial I've seen mentions how to inject MyGuard as a provider. How do I do this?

Manse answered 28/7, 2016 at 19:34 Comment(0)
G
12

My solution was to add the AuthGuard service to the providers in my AppModule metadata:

@NgModule({
    ...
    providers: [AuthGuard],
})
export class AppModule {}

To be able to use a service in the the whole app you need to provide it in the AppModule metadata. The "Service Providers" section on https://angular.io/docs/ts/latest/guide/ngmodule.html gave me the hint.

Guideline answered 13/10, 2016 at 20:51 Comment(2)
My problem was that the name of the class guard has wrapped with simple quote, like: providers: ['AuthGuard']Azide
Thanks, I added it to my sub modules and the problem is solved.Whitish
C
3

Your routes configuration should be like this:

export const APP_ROUTER_PROVIDERS = [
    MyGuard, <== notice this line
    provideRouter(AppRoutes )
];

and then

import { APP_ROUTER_PROVIDERS } from './app.routes';    
import { AppComponent } from './app.component';

bootstrap(AppComponent, [
    APP_ROUTER_PROVIDERS
])
Chengteh answered 28/7, 2016 at 19:39 Comment(0)
P
2

I have solved this problem by adding the 'MyGuard' in providers array

@NgModule({
  declarations: [
..........
],
providers: [MyGuard]
........
Procopius answered 18/6, 2018 at 13:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.