I have an app that uses multiple categories. Two of them are "solarpanels" and "inverters".
In a component, named stockitems, I have a table which lists the products of the selected category.
<ul class="list-group">
<li class="list-group-item d-flex justify-content-between align-items-center" *ngFor ="let stockitem of stockitems">
{{stockitem.name}}
<span class="badge bg-primary rounded-pill">X</span>
</li>
</ul>
When accessing the component, I know which category the user selected, but to fill the array 'stockitems' which generates the contents of my table, I use a service like 'SolarpanelService' or 'Inverterservice'. Now to decide which service to access, I use a switch/case-block :
switch(this.category)
{
case "solarpanels" :
this.SolarpanelService.getSolarpanel().subscribe(
(response :Solarpanel[]) => {
this.stockitems = response;
},
(error) => console.log('Error'),
() => console.log('ready')
);
break;
....
Now this works, but I was wondering whether I could actually compact the code so I don't have to write n case-blocks. In other words, I would like one code block that, depending on the selected category accesses the right service, method and model like :
this."SelectedService".get"SelectedMethod"().subscribe(
(response :"SelectedModel"[]) => {
this.stockitems = response;
},
(error) => console.log('Error'),
() => console.log('ready')
);
Where the "Selected..." would we SolarpanelService or InverterService or .... etc etc etc ...
Basically I want to cast a variable name to a string that is then used to access the right stuff. I think it's a long shot, but maybe it's possible, or maybe there's a whole other way of doing these things.
Thanks in advance !
