Angular2: cannot resolve all parameters when injecting a service into the guard

I am updating angular2 application on RC.7 and I hit it with security that checks user rights before allowing access to this page. Right now I have simplified the guard to just return true, and it still doesn't work - it looks like it can't find my appStateService, but I injected it into other components and services in my application and it works fine there.

Security code:

import { Inject, Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

import { AppStateService } from '../../appState';

@Injectable()
export class MonitorPermissionGuard implements CanActivate {

constructor(private appStateService: AppStateService, private router: Router) {}

canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    console.log('guard called');
    return true;
}

}

In my app.module.ts file, there are both AppStateService and MonitorPermissionGuard added to the providers array.

I get the following error in my console when starting the application:

metadata_resolver.js:523 Uncaught Error: Can't resolve all parameters for MonitorPermissionGuard: (?, Router).

Not sure what is going on here because I used appStateService throughout the application without any problems.

thank

EDIT: Code for AppStateService

@Injectable()
export class AppStateService {

public appState: AppStateModel;

constructor() {
    this.appState = new AppStateModel();
}

toggleSidenav() {
    this.appState.sidenavExpand = !this.appState.sidenavExpand;
}

clearSidenav() {
    this.appState.sidenavButtons = new Array<SidenavButton>();
}

addSidenavLink(buttonText: string, iconClass: string, route: string) {
    let sidenavButton: SidenavButton = new SidenavButton(buttonText, iconClass, route);
    this.appState.sidenavButtons.push(sidenavButton);
}

setPageTitle(pageTitle: string) {
    this.appState.pageTitle = pageTitle;
}

hasPermission(feature: string) {
    return this.appState.userPermissions[feature];
}

giveFeaturePermission(feature: string) {
    this.appState.userPermissions[feature] = true;
}

recantFeaturePermission(feature: string) {
    this.appState.userPermissions[feature] = false;
}

showInfo(message: string) {
    this.showMessage('INFO', message);
}

showWarning(message: string) {
    this.showMessage('WARNING', message);
}

showError(message: string) {
    this.showMessage('ERROR', message);
}

private showMessage(type: string, message: string) {
    this.appState.appMessage.type = type;
    this.appState.appMessage.message = message;
    this.appState.isMessageShown = true;
    setTimeout(() => { this.appState.isMessageShown = false; }, 2000);
}

}
+4

Source: https://habr.com/ru/post/1654583/


All Articles