I use an AuthService and an AuthGuard to log in/log out users and guard routes. The AuthService is used in the AuthGuard as well as in a LoginComponent. The AuthGuard is used to guard routes via CanActivate. When I try to run the app I get the following error:
zone.js:522 Unhandled Promise rejection: No provider for AuthService! ; Zone: angular ; Task: Promise.then ; Value: NoProviderError {__zone_symbol__error: Error: DI Error
at NoProviderError.ZoneAwareError
I have checked that the LoginComponent and AuthGuard both import the AuthService and inject it into the components via the constructor. I have also checked that the AuthService is imported into the AppModule file and added to the providers array so it can be used as a singleton service.
Edited to add code samples:
My App module contains the following:
@NgModule({
imports: [...],
providers: [..., AuthService, AuthGuard, ...],
declarations: [..., LoginComponent, EntryComponent ...],
bootstrap: [EntryComponent]
})
export class AppModule {
}
AuthGuard:
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { ApiConfig } from '../Api';
import { AuthService } from './authservice';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private authService: AuthService,
private router: Router,
private config: ApiConfig
) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
console.log(this.isAuthenticated());
if (this.isAuthenticated()) {
if (this.config.defined) {
return true;
} else {
this.authService.setConfig();
return true;
}
} else {
this.router.navigate(['/Login']);
return false;
}
}
// Checks if user is logged in
isAuthenticated() {
return this.authService.userLoggedIn();
}
}
LoginComponent constructor:
constructor(
private router: Router,
private notifications: Notifications,
private authService: AuthService
) {}
AuthService:
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { ApiConfig } from '../Api';
@Injectable()
export class AuthService {
constructor(
private http: Http,
private router: Router,
private config: ApiConfig
) {
this.apiRoot = localStorage.getItem('apiRoot');
}
...
}