Im getting this error:
EXCEPTION: Error in ./AppComponent class AppComponent - inline template:0:0 caused by: No provider for Router!
Babar Bilal's answer likely worked perfectly for earlier Angular 2 alpha/beta releases. However, anyone solving this problem with Angular release v4+ may want to try the following change to his answer instead (wrapping the single route in the required array):
RouterModule.forRoot([{ path: "", component: LoginComponent}])
Please do the import like below:
import { Router } from '@angular/Router';
The mistake that was being done was -> import { Router } from '@angular/router';
If you created a separate module (eg. AppRoutingModule
) to contain your routing commands you can get this same error:
Error: StaticInjectorError(AppModule)[RouterLinkWithHref -> Router]:
StaticInjectorError(Platform: core)[RouterLinkWithHref -> Router]:
NullInjectorError: No provider for Router!
You may have forgotten to import it to the main AppModule
as shown here:
@NgModule({
imports: [ BrowserModule, FormsModule, RouterModule, AppRoutingModule ],
declarations: [ AppComponent, Page1Component, Page2Component ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
I have also received this error when developing automatic tests for components. In this context the following import should be done:
import { RouterTestingModule } from "@angular/router/testing";
const testBedConfiguration = {
imports: [SharedModule,
BrowserAnimationsModule,
RouterTestingModule.withRoutes([]),
],
I had the error of
No provider for Router
It happens when you try to navigate in any service.ts
this.router.navigate(['/home']);
like codes in services cause that error.
You should handle navigating in your components. for example: at login.component
login().subscribe(
(res) => this.router.navigate(['/home']),
(error: any) => this.handleError(error));
Annoying errors happens when we are newbie :)
Nothing works from this tread. "forRoot" doesn't help.
Sorry. Sorted this out. I've managed to make it work by setting correct "routes" for this "forRoot" router setup routine
import {RouterModule, Routes} from '@angular/router';
import {AppComponent} from './app.component';
const appRoutes: Routes = [
{path: 'UI/part1/Details', component: DetailsComponent}
];
@NgModule({
declarations: [
AppComponent,
DetailsComponent
],
imports: [
BrowserModule,
HttpClientModule,
RouterModule.forRoot(appRoutes)
],
providers: [DetailsService],
bootstrap: [AppComponent]
})
Also may be helpful (spent some time to realize this) Optional route part:
const appRoutes: Routes = [
{path: 'UI/part1/Details', component: DetailsComponent},
{path: ':project/UI/part1/Details', component: DetailsComponent}
];
Second rule allows to open URLs like "hostname/test/UI/part1/Details?id=666" and "hostname/UI/part1/Details?id=666"
Been working as a frontend developer since 2012 but never stuck in a such over-complicated thing as angular2 (I have 3 years experience with enterprise level ExtJS)