I don't think Gunther's answer here is completely correct. If I correctly understood the Hongbo Miao problem, this can be "easily" achieved. If you want to get a new instance of the service with each injection, you will need to use useFactory instead of the provider useClass configuration.
Then, if you get a provider error for "token1" in Service2 because it is not configured on the correct injector, the parent or parent element of OneComponent ... where Service2 is entered.
Edit:
To do this, you will need to identify the Service provider and Service2 at the root component (for example). In this case, everyone will use the same service instance.
If you want to have different instances in each component, identify the suppliers at the component level where the services are used.
@Component({ providers: [Service, Service2], // Other config props }) export class RootComponent { } @Component({ // Config props }) export class OneComponent { constructor(public service: Service) {} methodx() { this.service... } } @Component({ // Config props }) export class TwoComponent { constructor(public service: Service2) {} methodx() { this.service... } } @Injectable() export class Service2 { constructor(public service: Service) { } }
Using @Inject('StringToken') is not the best thing you do, and it is not recommended. Instead, use a type token (as done in the code above).
Resources
source share