2

I have a service like the following:

import {Injectable} from 'angular2/core';
import {Router, RouteParams} from 'angular2/router';

@Injectable()
export class QService {
  /* A service to handle a query (q) in the search string.
   */
  constructor(
      private _router:Router,
      routeParams:RouteParams
    ) {
    /* Set this._q from the search string.
     */
    this._q = routeParams.get('q');
  }

  private _q:string
  get q():string {
    return this._q;
  }
  set q(q:string) {
    this._q = q;
    // TODO Add q back to the search string.
  }
}

Unfortunately, no matter how I use this service, I get an error along the lines of No provider for RouteParams. I'm stumped. Is there some recommended or simple way of doing this I've missed?

astex
  • 1,045
  • 10
  • 28
  • Did you add `ROUTER_PROVIDERS` to `bootstrap(AppComponent, [ROUTER_PROVIDERS])`? – Günter Zöchbauer Mar 18 '16 at 23:00
  • This comment is longer than necessary because of Stack Overflow's somewhat strange rules. Yes I do. – astex Mar 18 '16 at 23:04
  • Can you try: QService.params = [[Router],[RouteParams]] at the very end of your code? Also, I add injectables: [RouteParams], but this inside my @Component. May be you can try this as well – Mohy Eldeen Mar 19 '16 at 00:20

1 Answers1

1

I think that you need to specify this service at the level of a component (involved in routing) within its providers attribute and not when bootstrapping your application:

@Component({
  (...)
  providers: [ QService]
})
export class... 

As a matter of fact RouteParams only applies in the context of a component and not globally to the application. So the application injector doesn't have knowledge of this provider since it's present in a child injector only (a component one).

This is linked to dependency injection and hierarchical injectors. See this question for more details:

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • I do use the service as a provider as indicated. If I remove anything to do with routing, the service works as expected. However, it seems like terrible isolation of concern to have a component wrap the service and handle changes to the search string. Especially since I also want the search string to update when q changes. I'd be happy to see the "correct" way that angular has prescribed to do this. – astex Mar 19 '16 at 17:32