How to use providers in the service?

I need to use multiple instances of the same service.

Usually, when I use one instance of this service in a component, I write like this:

@Component({ selector: 'one-component', providers: [provide("token1", {useClass: Service})], template: ` <h1>App</h1> ` }) export class OneComponent { constructor(@Inject('token1') service:Service) {} } 

But now I need to use this service in Service2, I write like this:

 export class Service2 { constructor(@Inject('token1') service:Service) {} } 

As you know, this shows:

No provider

Because Service2 does not have providers: [provide("token1", {useClass: Service})] . But where can I add it since it does not have @Component ?

thanks

+6
source share
3 answers

Sadly configuring services this way is not currently supported, and there is currently no plan to add support for https://github.com/angular/angular/issues/5622

+2
source

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

0
source

I fixed this error (using service B in service A) by declaring two services in the providers array app.module.ts .

 @NgModule({ declarations: [...], imports: [...], providers: [ ServiceA, ServiceB, ], bootstrap: [...], }) 
0
source

All Articles