I have components B
, C
, D
that inherit from class A
.
I want to use a service in class A
, but I don't know how to inject it, without injecting it from its children.
What I tried is a normal injection:
constructor(pageName: string = null, translate: TranslateService) {
But when I do super()
to construct class A
, it throws an error because I didn't supply a second parameter.
Is there a way to inject into a parent class using Angular 2?
The Angular version I am forced to use is: 2.2.1
EDIT:
Some example case: I have many pages, each can show a loader. Instead of injecting the loader every time, and manage the loader from every page, I wanna do:
export class BaseComponent {
constructor(private loader: LoadingService) {}
showLoading() {
this.loader.show();
}
}
And then to inherit from the component itself:
@Component({
selector: "page-login",
providers: [UsersService],
templateUrl: "login.html"
})
export class LoginPage extends BaseComponent {
constructor(private usersService: UsersService) {
super();
}
}
Now LoginPage
has a method showLoading
from it's parent.
showLoading() { this.loader.show(); }
, there may be better ways to do that. Since the question is XY problem (you're trying to do a thing which doesn't play well with the framework itself), explaining the case thoroughly helps to get the best solution. The accepted answer is a known workaround - and a hack. Its usage usually indicates that idiomatic solution wasn't found. There may or may not be negative effects of it (global injector can hurt testability, for instance). – Estus Flask Feb 25 '17 at 23:06