'Upgrading to Angular 5 NullInjectorError: No provider for
Im trying to upgrade to angular 4, but when running the code I get an error:
ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[AuthenticatedGuard -> AuthService]:
StaticInjectorError(Platform: core)[AuthenticatedGuard -> AuthService]:
NullInjectorError: No provider for AuthService!
The error says "No provider for AuthService", but in the very component that I'm navigating from I inject and successfully make use of my AuthService. Here are the relevant source files:
app.module.ts
import { AuthService } from '../../services/auth.service';
import { AuthenticatedGuard } from '../../utility/authenticated.gaurd'
@NgModule({
imports:[ ... ],
declarations: [ ... ],
providers: [ AuthService, AuthenticatedGuard ]})
export class AppModule { }
authenticated.gaurd.ts
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthService } from '../services/auth.service.js';
@Injectable()
export class AuthenticatedGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
return true;
}
}
app-routing.module.ts
import { AdminComponent } from '../../components/admin/admin.component';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: 'admin', component: DashboardComponent, canActivate: [AuthenticatedGuard]},
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
Any ideas where this error could mysteriously come from? I assume something has changes from angular 4 - 5 but I'm not sure what?
Solution 1:[1]
First step:
import { AuthService } from '../services/auth.service';
Second step:
providers: [
AuthService
],
Solution 2:[2]
Solution 3:[3]
@Injectable({ providedIn: 'root' }) export class YourService {}
My problem was this, I created the service without terminal shortcuts and added the injectable decorator but forgot to provide it in the root
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jeremy Caney |
| Solution 2 | Fazeel Mehar |
| Solution 3 | EngDanielMendes |

