1

I can typically inject any provider into my components, but is this limited to components? Is there any way to inject ActivatedRoute into a regular class which is used in this context:

app.module.ts

@NgModule({
  ...
  providers: [
    AuthenticatedRequestOptions,
    { provide: RequestOptions, useClass: AuthenticatedRequestOptions }
  ],
  ...
})

authenticated-request-options.model.ts

@Injectable()
export class AuthenticatedRequestOptions extends BaseRequestOptions {
    constructor(@Inject(ActivatedRoute) public route: ActivatedRoute) {
        super();
        console.log('route', this.route);
    }
}
parliament
  • 20,000
  • 37
  • 141
  • 232

2 Answers2

1

Just add it as parameter to your constructor

constructor(route: ActivatedRoute, private injector: Injector) {}

AuthenticatedRequestOptions needs to be provided somewhere @Component(), @NgModule(), ... and the class needs to have the @Injectable() decorator

@Injectable()
export class AuthenticatedRequestOptions extends BaseRequestOptions {

and the class needs to be injected itself.
If you create an instance with new AuthenticatedRequestOptions(...) Angulars DI is not involved and you need to pass parameters yourself.

Günter Zöchbauer
  • 558,509
  • 191
  • 1,911
  • 1,506
  • As I mentioned, this didn't work either. injector is undefined in my example – parliament Nov 09 '16 at 13:45
  • I extended my answer. – Günter Zöchbauer Nov 09 '16 at 13:47
  • I updated my question with new code that follows these suggestions and still injects nothing. – parliament Nov 09 '16 at 13:55
  • You don't need `@Inject(ActivatedRoute)` if the type is the same `route:ActivatedRoute`. It's just redundant. Otherwise I can't tell from the code you provided. The root cause has to be somewhere else. The code in the question is fine now. Can you reproduce in a Plunker? Plunker provides a ready-to-use Angular2TS template with the "New" button. – Günter Zöchbauer Nov 09 '16 at 13:57
  • That's so greate about Plunker. Just creating one solves losts of issues ;-) – Günter Zöchbauer Nov 09 '16 at 14:06
  • 1
    Indeed, I realized the issue while making it. You're right, the issue was elsewhere. I needed to extend `RequestOptions` not `BaseRequestionOptions`. Commented on this here, where I got the original code: http://stackoverflow.com/a/39866166/1267778 – parliament Nov 09 '16 at 14:09
1

@Inject allows to inject dependencies into providers even if they don't have @Injectable decorator, the proper syntax is:

export class AuthenticatedRequestOptions extends BaseRequestOptions {
   constructor(@Inject(ActivatedRoute) private route: ActivatedRoute) {
   ...

In order for a provider class to make use of type annotation for DI it should have @Injectable decorator:

@Injectable()
export class AuthenticatedRequestOptions extends BaseRequestOptions {
   constructor(private route: ActivatedRoute) {
   ...
Estus Flask
  • 179,509
  • 61
  • 360
  • 499