0

I have a Parent Component calling the two same Child components. The child component contains a SearchForm and Grid.

The two search grids are shown side by side, in iframe format. Allow users conduct two searches.

When doing a grid search, they seem to be utilizing the same service, and populating the two grids. Doing a search in one grid component, populates data in the other component. Searches are being cloned.

How do I make sure that each child component uses a different service instance? Child components are called in html selectors.

<div>
   <app-product-search-grid></app-product-search-grid>

   <app-product-search-grid></app-product-search-grid>
</div>

Not sure how to apply this answer, Using multiple instances of the same service

The child component looks as this,

export class ProductSearchGridComponent

  constructor(
    private productGridService: ProductGridService,

I really don't want to change the constructor if possible, as it may affect other people code.

1 Answers1

0

If you need a separate instance of the service in both children, you can provide your service at the component level:

@Component({
/* . . . */
  providers: [ProductGridService]
})
export class ProductSearchGridComponent {
  constructor(private service: ProductGridService) { }
 }
code-gorilla
  • 2,231
  • 1
  • 6
  • 21
  • I am calling the child components through html selectors, so how do I inject service? Thanks –  Oct 09 '20 at 06:14
  • You dont have to change anything else, just provide the service in the child component instead of in the module. The service can the be injected through the constructor as usual. – code-gorilla Oct 09 '20 at 06:16
  • can you display more code? because productGridService is already in the constructor, do you want me to remove it in the constructor? what is "YourService" by the way? Just need more code to display, and I'll understand, thanks –  Oct 09 '20 at 06:18
  • or all I need to write is providers: [ProductGridService] , and I'm good to go? –  Oct 09 '20 at 06:19
  • I made my answer more explicit to your example. In the end you just have to add your service to the providers array of your child component. – code-gorilla Oct 09 '20 at 06:22
  • strange, adding this line providers: [ProductGridService], the searches do Not work anymore –  Oct 09 '20 at 06:25