lox
lox

Reputation: 1622

An Angular service which is not shared and instantiated with a parameter

I have an Angular Service (myService) which is injected into the constructor of a number of components and other services.

I would like each of these usages to have their own instance of myService, so no data is shared.

I would also like myService to be instantiated with a parameter defining some behaviour in it. So each place it is used in a constructor, I would like to be able to specify this parameter.

Is this possible?

Upvotes: 1

Views: 179

Answers (1)

taras-d
taras-d

Reputation: 1827

Add your service into providers of the component. This will create own service instance per component instance. For example:

@Component({
  // ...
  providers: [MyService]
})
export class MyComponent  {
  // ...
}

You can specify service parameters using FactoryProvider. Example:

@Component({
  // ...
  providers: [
    {
      provide: MyService,
      useFactory: () => new MyService('param1') // create service with 'param1' for MyComponent instances
    }
  ]
})
export class MyComponent  {
  // ...
}

Upvotes: 2

Related Questions