Reputation: 3580
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?
Upvotes: 6
Views: 15377
Reputation: 15
in your app.module.ts
providers: [AuthService,
{ provide: FIREBASE_OPTIONS, useValue: environment.firebase},
AuthGaurdService],
bootstrap: [AppComponent]
})
Write this, works for me
Upvotes: 0
Reputation: 1
@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
Upvotes: 0
Reputation: 61
Please add it in providers in app.module.ts
providers: [
AuthService
],
Upvotes: 1
Reputation: 71
First step:
import { AuthService } from '../services/auth.service';
Second step:
providers: [
AuthService
],
Upvotes: 7
Reputation: 25161
Change this:
import { AuthService } from '../services/auth.service.js';
To this:
import { AuthService } from '../services/auth.service';
Remove the .js from the end of the import in the authenticated.gaurd.ts. The file extension is not needed for imports.
Upvotes: 3