angularangular2-routingangular2-router3

No provider for ActivatedRoute - Angular 2 RC5


After upgrading to Angular 2 RC5 (from RC4) it seems I can no longer inject ActivatedRoute into my components.

ORIGINAL EXCEPTION: No provider for ActivatedRoute!

Here's the relevant piece of code:

import { Component } from '@angular/core';

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

declare var module: {
  id: string;
};

@Component({
  moduleId: module.id,
  selector: 'mds-app',
  templateUrl: 'app.component.html',
  styleUrls: [
      'app.component.css'
  ],
  directives: []
})
export class AppComponent { 

  constructor(private _route: ActivatedRoute) {
    this._route.params.subscribe(params => console.log(_route));
  }
}

and here's my app.module.ts:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { CommonModule }  from '@angular/common';
import { Routes, RouterModule }  from '@angular/router';

import { AppComponent }  from './app.component';

import { 
    routing, 
    appRoutingProviders 
} from './app.routing';

@NgModule({
  imports:      [ BrowserModule, CommonModule, RouterModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ],
  providers:    [ appRoutingProviders ]
})
export class AppModule { }

I checked the "Tour of Heroes" example and they do the exact same thing, there is no provider declaration for ActivatedRoute so what is going on here I wonder?


Solution

  • I was browsing through Angular 2 issues on GitHub and found the solution to the above problem out of sheer luck (see here).

    I needed to add routing (see import above) to imports in NgModule, i.e.

    @NgModule({
      imports:      [ BrowserModule, CommonModule, RouterModule, routing ],
      declarations: [ AppComponent ],
      bootstrap:    [ AppComponent ],
      providers:    [ appRoutingProviders ]
    })
    

    Seems Angular 2's error messages just got more confusing than they already have been.

    I hope this answer is of some use to someone, I was about to pull my hair out already.

    EDIT: By popular request, here's a snippet for the imported routing (off the top of my head, as I'm off work this week, let me know in the comments if there are any issues with it):

    app.routing.ts:

    export routes: Routes = [
       { path: 'sales', component: SalesComponent }
    ];
    
    export routing = RouterModule.forRoot(routes);
    

    and in your app.module.ts you'd import this as follows:

    import { routing } from 'app.routing'