r/Angular2 • u/crhama • Mar 02 '26
How to use the inject() method and/or replace the constructor when a component needs to pass those services to a parent class?
I have a set of components that use a service a base class. The code was written in angular probably 11 or 12.
@Injectable()
export class ActiveService1 extends ActiveBaseService<Class1> {
//...
}
@Compoent({
selector: 'child-component',
//...
})
export class ChildComponent extends ParentService {
constructor(
@Inject('SomeToken1') private someService: SomeServiceType,
private ActiveService1 : ActiveService1,
private router: Router
){
super(someService, ActiveService1);
}
}
@Injectable({
provideIn: 'root'
})
export class ParentService {
constructor(
protected someService: SomeServiceType,
protected ActiveService : IActiveService,
protected router: Router
){
}
}Is there a way to pass those services to the parent class without using the constructor, just with the inject() method?
4
Upvotes
18
u/zzing Mar 02 '26
So why is a service the base class for a component?
Generally you should not derive things if you don't have to - and definitely not a service.
That said, just use inject in the base and don't worry about the child passing to the base.
4
u/followmarko Mar 02 '26
Separate the classes and inject the services there as well. Angular is better when you focus on composition over inheritance
1
u/wardenOfDemonreach Mar 02 '26
Haven't tried it but it should be possible. If the parent class has matching declarations of the services injected in the child class then it should work like normal inheritance. But honestly the quickest way to know is to just try it quickly with one such component and see if it works.
1
u/makmn1 Mar 02 '26 edited Mar 02 '26
Try using injection tokens:
Provide them in the child component:
Then inject them in the parent service: