Angular 6 Error “NullInjectorError: No provider for Router!”

夙愿已清 提交于 2019-12-05 13:59:09

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!

In case someone is using npm link(s), the following does the job:

In .angular-cli.json add/replace:

"defaults": {
    "styleExt": "css",
    "component": {},
    "build": {
        "preserveSymlinks": true
    }
}

You need to add a <router-outlet></router-outlet>

The tag <router-outlet></router-outlet> is the place where your app is going to render the different routes. For example, in the app.component.html you can have:

<header>
    <bt-toolbar></bt-toolbar>
</header>

<main>
    <router-outlet></router-outlet>
</main>

With this template I have a top bar always visible and below is the content of the diferent routes.

Add to your app.module.ts this in the imports array:

RouterModule.forRoot([
      { path: 'SendNotification', component: YourComponent }

In my case, I only put:

<base href="/">

In my head tag in the index.html file.

...
<head>
  ...
  <title>Name of page</title>
  <base href="/">
</head>
...

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!