Reputation: 7143
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?
Upvotes: 1
Views: 2133
Reputation: 9786
To begin with, you should not need to have more than one instance of a service in angular. It is a DI framework and as such you should(in most of cases) have a single instance of each service.
The thing that may lead you think that you eventually need to have a specific/separate instances of the service for each class is that with the statement:
public guidanceResponseBS: BehaviorSubject<GuidanceResponse>;
you are coupling the concept of data (state) with that of a business logic
. Your services are not supposed to contain/save data, at least not the once that you intend as business logic
ones.
Now, there are also services that will contain data, but that is generally done for the purpose of sharing the data among more components in the applicaiton. Generally, in these cases, you load the data at same stage and you save it in a service to make it available for future use.
Upvotes: 0
Reputation: 8468
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]
})
Upvotes: 4