parliament
parliament

Reputation: 22914

ng2 - injecting a provider into a regular class

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

Upvotes: 1

Views: 504

Answers (2)

Estus Flask
Estus Flask

Reputation: 222369

@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) {
   ...

Upvotes: 1

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657158

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.

Upvotes: 1

Related Questions