I have two services S1 and S2 in Angular
export class S1 {
constructor(private s2: S2) {
// ...
}
}
I want to create instance of S2 that is only scoped for S1 (the same as we do for Components)
Any suggestion on how to do that?
I am not pretty sure that i get what you want but let me break it down as following:
You can inject a service into another service as following:
@Injectable()
export class First {
}
@Injectable()
export class Second {
constructor(@Inject(First) first:First){
}
}
Note that you have to provide your services somewhere and as default you might provide them in your app root
I don't think this is possible because the decorator "@Injectable" only adds the providedIn metadata that defines which injectors will provide the injectable by associating it with an @NgModule. (see documentation)
Maybe if you share some concrete use-case we can see if there's any other workaround, but probably there's a shortage in your app structure design.
I want to create instance of S2 that is only scoped for S1 (the same as we do for Components)
Well, that's exactly what you do. You provide S1 and S2 in the scope of a component.
@Component({
...
viewProviders: [ S1, S2 ]
})
export class MyComponent { ... }
This means that S1 and S2 will be unique instances accessible to children of the MyComponent.
It is not possible for have a single instance of S1 that receives a different instance of S2, because you're defining the dependency in the constructor.