1

While Implementing CanActivate Guard Im Getting error as : No provider for HRComponent

import { Component, OnInit } from "@angular/core"
import { ActivatedRoute, CanActivate } from "@angular/router"
import { LoginService } from "../../services/loginservice"
@Component({
    templateUrl:"../../../templates/hrmodule/hrmodule.html"
})
export class HRComponent implements CanActivate {
    constructor(private Loginservice: LoginService) { }
    canActivate(){
        debugger;
        alert('Active');
        return true;
    }
}

This is my HRmodile.ts

import { NgModule } from "@angular/core"
import { RouterModule} from "@angular/router"
import { HrRoute } from "../../app/route/hrroute"
import { HRComponent } from "../../app/component/hrcomponent/hrcomponent"
import { LoginService } from "../../app/services/loginservice"
@NgModule({
    imports: [RouterModule.forChild(HrRoute)],
    declarations: [HRComponent],
    bootstrap: [HRComponent ],
    providers: [LoginService]
})

export class HRmodule {
}

This is HrRoute Here i wrote canActivate

import { HRComponent } from "../component/hrcomponent/hrcomponent"
export const HrRoute = [
    { path: "Add", component: HRComponent, canActivate: [HRComponent]}
];

This is My Html Link

    <a [routerLink]="['HrModule/Add']" class="btn btn-primary btn-sm">HrModule</a>

{ path: 'HrModule', loadChildren: '../../module/hrmodule/hrmodule#HRmodule' },

1 Answers1

0

A guard must be a service not a component.

@Injectable()
export class HRService implements CanActivate {
    constructor(private Loginservice: LoginService) { }
    canActivate(){
        debugger;
        alert('Active');
        return true;
    }
}

And NOTE that it then cannot be your bootstrapped component in your module. By convention the bootstrapped component is "AppComponent"

@NgModule({
    imports: [RouterModule.forChild(HrRoute)],
    bootstrap: [ @@@ YOU NEED SOMETHING ELSE HERE @@@ ],
    providers: [LoginService, HRService ]
})
export class HRmodule {
}

See the docs here for more information and for an example: https://angular.io/api/router/CanActivate

And here: https://angular.io/guide/router#milestone-5-route-guards

DeborahK
  • 57,520
  • 12
  • 104
  • 129
  • After Decorationg @Injectable() is also I'm getting Same Error –  Aug 20 '17 at 06:28
  • The error is telling you that you don't have a service provider for it. That means that you need to specify it in one of your Angular modules in the providers array. Did you fix your Angular Module? See the note I have in my answer. I tried pasting an updated version of your Angular Module, but had no idea what to put for the bootstrap component. – DeborahK Aug 20 '17 at 06:29
  • Im using LazyLoading For that i Used bootstrap as bootstrap: [HRComponent ], –  Aug 20 '17 at 06:30
  • Thank a Lot @Deborkah –  Aug 20 '17 at 06:31