[angular] No provider for Router?

Im getting this error:

EXCEPTION: Error in ./AppComponent class AppComponent - inline template:0:0 caused by: No provider for Router!

This is my app component:

import {Component} from '@angular/core';
import {LoginComponent} from './login/components/login.component';
@Component({
    selector: 'my-app',
    template: '<login></login>',

})
export class AppComponent {

}

I tried this in my app module:

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

  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    LoginModule,
    RouterModule
  ],
  bootstrap: [AppComponent, RouterModule]

But then i get this error:

Error: Error: No Directive annotation found on RouterModule

I found some examples but they use router-deprecated, and i dont have that folder. Do i need that or what? Any suggstion?

UPDATE:

This is my app.module:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { LoginModule } from './login/login.module';
import { RouterModule } from '@angular/router';
//import 'rxjs/Rx';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    LoginModule,
    RouterModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component:

import {Component} from '@angular/core';
import {LoginComponent} from './login/components/login.component';
@Component({
    selector: 'my-app',
    template: '<login></login>',

})
export class AppComponent {

}

And then i have login.component:

import {Component, EventEmitter, Input, OnChanges} from '@angular/core';
import {Observable} from 'rxjs/Rx';
import { LoginService } from '../services/login.service';
import { Login } from '../model/login'
import {Router} from '@angular/router';
@Component({
    selector: 'login',
    templateUrl: 'login-form',

})
export class LoginComponent {
  // Constructor with injected service
      constructor(
          private loginService: LoginService,
          private router: Router
          ){}

      submitLogin(values){

          // Variable to hold a reference of addComment/updateComment
             let loginOperation:Observable<any>;
             loginOperation = this.loginService.Login(values);
             loginOperation.subscribe(
                function(response) { console.log("Success Response" + response)},
                function(error) { console.log("Error happened" + error)},
                function() {
                   console.log("the subscription is completed");
                     this.router.navigate(['/About']);

                 }
            );

           }
}

Maybe problem is in this line:

 this.router.navigate(['/home']);

This is my login.module:

import { NgModule }       from '@angular/core';
import { BrowserModule }  from '@angular/platform-browser';
import { FormsModule }    from '@angular/forms';
import { HttpModule, JsonpModule } from '@angular/http';
import { LoginComponent } from './components/login.component';
import { RouterModule } from '@angular/router';

import { LoginService } from './services/login.service';


@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
     HttpModule,
    JsonpModule,
    RouterModule  


  ],
  declarations: [
    LoginComponent
  ],

  providers: [
      LoginService
  ],

  exports:[
    LoginComponent
  ]

})
export class LoginModule {
}

This question is related to angular routes

The answer is


Please use this module

RouterModule.forRoot(
  [
    { path: "", component: LoginComponent}
  ]
)

now just replace your <login></login> with <router-outlet></router-outlet> thats it


Please do the import like below:

import { Router } from '@angular/Router';

The mistake that was being done was -> import { Router } from '@angular/router';


I had a routerLink="." attribute at one of my HTML tags which caused that error


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 :)


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([]),
  ],

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)


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}])

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 { }