Search code examples
angulartypescriptangular-servicesangular10

Angular Use Multiple Instances of Service In Parent to Child Components


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.


Solution

  • 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) { }
     }