I have an application which has multiple cases of a fairly similar master-details view with a search box. So I decided to wrap the common functionality into its own module with communication between the components achieved through a service. Here is the hierarchy:
MyGenericGridModule
SearchComponent
MasterGridComponent
DetailsComponent
GridService <-- stateful
AppModule
CitiesGridComponent
RetailersGridComponent
I intend to create multiple views of MyGenericGridComponent
where the layout differences will be achieved through css. Here is quick illustration:
How do I ensure that I provide separate instances of the GridService
to both dependent components?
I haven't found reading material so far that showcases this scenario. What I have read mentions Services should be shared and singletons. This leads me to believe I am tackling this problem incorrectly. Is there a more suitable pattern I can structure the components?
It will create multiple instances of a service. Every time a new instance of provided service will be created when a component is used inside another component.
We have three way of creating Instances.
There are two ways you can do it Angular.
Injecting the GridService
at the component level would mean you get a different instance for each component, rather than a single instance from the parent injector e.g.:
import { Component, OnInit } from '@angular/core';
import { GridService } from '../grid.service';
@Component({
selector: 'app-cities-grid',
templateUrl: './cities-grid.component.html',
styleUrls: ['./cities-grid.component.css'],
providers: [GridService]
})
export class CitiesGridComponent implements OnInit {
constructor(gridSvc: GridService) { }
In addition to the links provided in the comments, this link to providing services in components from the Angular documentation seems aligned with your scenario.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With