Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to provide separate service instances for multiple child components in Angular 2

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: enter image description here 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?

like image 459
tony Avatar asked Feb 20 '18 23:02

tony


People also ask

Can we create multiple instances of service in Angular?

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.

How many instances create of service in Angular?

We have three way of creating Instances.

How many ways we can pass the data from parent to child in Angular?

There are two ways you can do it Angular.


1 Answers

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.

like image 164
Garth Mason Avatar answered Oct 16 '22 14:10

Garth Mason