Angular 6 Error "NullInjectorError: No provider for Router!" Angular 6 Error "NullInjectorError: No provider for Router!" asp.net asp.net

Angular 6 Error "NullInjectorError: No provider for Router!"


First import RouteModule in app.module.ts

import { RouterModule, Routes } from '@angular/router';

And use it like below: (You only import RouterModule but need to add forRoot([]) also.)

imports: [    RouterModule.forRoot([])    // other imports here  ]

If you have any routes use them like below. This sample code from Angular DOC

const appRoutes: Routes = [  { path: 'crisis-center', component: CrisisListComponent },  { path: 'hero/:id',      component: HeroDetailComponent },  {    path: 'heroes',    component: HeroListComponent,    data: { title: 'Heroes List' }  },  { path: '',    redirectTo: '/heroes',    pathMatch: 'full'  },  { path: '**', component: PageNotFoundComponent }];@NgModule({  imports: [    RouterModule.forRoot(      appRoutes,      { enableTracing: true } // <-- debugging purposes only    )    // other imports here  ],  ...})export class AppModule { }

And in your main Component (app.component.html) add <router-outlet></router-outlet>

Hope this will help you!


For those also struggling, with the cryptic/unhelpful error messages from the Angular compiler, make sure you have this somewhere:

RouterModule.forRoot([])

I was only using RouterModule.forChild([]), adding a forRoot() in one of the modules fixed the error.


If you are using

RouterModule.forChild(routes)

try it to replace with

RouterModule.forRoot(routes)