Reputation: 22914
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
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
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