Search code examples
angulardependency-injectionangular2-services

Angular2 injector causing Exception No Provier For Router error


I have the following code in my Angular2 app.component.ts

import { Component , OnInit} from '@angular/core';
import { WebService } from './webservices/webservices.services';
import { Http, Response } from '@angular/http';
import { Router } from '@angular/router';
import {HttpModule} from '@angular/http';
@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css'],
  providers: [WebService]
})
export class AppComponent implements OnInit {

  //constructor(private http: Http,  private webservice: WebService/*, private router: Router*/) { }
  title: string = 'My first angular2-google-maps project';
  lat: number = 45.478418;
  lng: number = -122.209007;
  public ngOnInit(){

  }
/*  public getData(){
    this.webservice.getDataFromBackend()
      .subscribe(
      (data) => this.handleData(data),
     // (err) => this.logError(err),
      () => console.log('got data')
      );
  }

    private handleData(data: Response) {
    if (data.status === 200) {
      let receivedData = data.json();
      console.log(receivedData);
    }
    console.log(data.json());
  }
*/




}

When I uncomment the constructor, I get a bunch of errors in my browser (commented out the constructor works) like

EXCEPTION: No provider for Router! and

Error: Uncaught (in promise): Error: DI Error BaseError@http://localhost:4200/vendor.bundle.js:25127:20 [angular]

. Why is this?

EDIT: app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ApplicationRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HttpModule } from '@angular/http';
import { AgmCoreModule } from 'angular2-google-maps/core';



@NgModule({
  imports: [
    BrowserModule,
    CommonModule,
    FormsModule,
    HttpModule,
    AgmCoreModule.forRoot({
      apiKey: 'Google Maps API Key'
    })
  ],
  providers: [],
  declarations: [ AppComponent ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

Solution

  • You forgot to import RouterModule

    @NgModule({
      imports: [
      BrowserModule,
      CommonModule,
      FormsModule,
      HttpModule,
      RouterModule // <== here
      // ...
      ],
    })