Search code examples
angularangular-dependency-injection

Provide Unique Service Instance in Every Component


I have a situation where I want to be able to have multiple widget components used on the page at the same time. I want to isolate the ContainerComponent dependencies so that each ContainerComponent instance references unique service instances.

For example I would like every instance of the following component to have a unique instance of the "FhirService":

export class ContainerComponent implements OnInit, OnDestroy, AfterViewInit {
...
constructor(private _fhir: FhirService, private _questionnaireService: QuestionnaireService, private cdr: ChangeDetectorRef) {}

Service definition:

@Injectable({
  providedIn: 'root'
})
export class FhirService {
  public guidanceResponseBS: BehaviorSubject<GuidanceResponse>;

  constructor(private _http: HttpClient, private _settingsService: SettingsService) {
    this.guidanceResponseBS = new BehaviorSubject<GuidanceResponse>(null);
  }

...

How is this done?


Solution

  • If you want to provide unique service instance to diffrent component, You will have to add the service In the @Component() decorator for a component. You should add these services to providers array for child Module declarations or to component declaration:

    You can configure injectors with providers at different levels of your app, by setting a metadata value in one of three places:

    In the @Injectable() decorator for the service itself.

    In the @NgModule() decorator for an NgModule.

    In the @Component() decorator for a component.

    EX:

     @Component({
      selector: 'app-hero-list',
      template: `
        <div *ngFor="let hero of heroes">
          {{hero.id}} - {{hero.name}}
        </div>
      `,
     providers: [myService]
    })