Reputation: 170
Currently I am working on a project where I need a table component which can be implemented as ChildComponent in multiple ParentComponents. The ParentComponents can provide data with different services.
Example given: For ComponentA the table shows data from ServiceA and for ComponentB the table shows data from ServiceB.
To do that my TableComponent has a @Input() variable called dataService:
_dataSubscription: Subscription;
@Input() dataService: DataService;
// DataService is an abstract class. ServiceA and ServiceB are implenting this class.
In ngOnInit() I am subscribing to dataService:
this._dataSubscription = this.dataService.getData().subscribe(
(response) => {
console.log(response)
}
);
Furthermore I am unsubscribing to dataService whenever the user switches between the ParentComponents:
ngOnDestroy(): void {
this._dataSubscription.unsubscribe()
}
In ParentComponentA the first service gets injected like that:
constructor(public serviceA: ServiceA){}
And it is passed to the table in .html with:
<app-table [dataService]="serviceA" #table></app-table>
(I do the same for ParentComponentB but instead of using "serviceA: ServiceA" I am using : "serviceB: ServiceB")
I know that its not looking that good but it works pretty well. The only problem is that whenever the user switches from ParentComponentA to ParentComponentB both .getData() methods are called and console.log prints both respone. This could be a problem when the data size is getting bigger and bigger. Is there anyway how to solve this problem?
I thought that unsubscribing in ngOnDestroy is working, but it had no effect - Still console.log prints the results of both calls
Thanks in advance
Upvotes: 0
Views: 44
Reputation: 21
Why you are passing the service to the child ?
You can simply inject the service to the child too by passing it in constructor
In ChildComponent do :
constructor(private serviceA: ServiceA){}
Note: You can inject a single service to multiple components
Upvotes: 0