Home > front end >  Using variable name to access service,model,
Using variable name to access service,model,

Time:05-16

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 >
            <li  *ngFor ="let stockitem of stockitems">
             {{stockitem.name}}
              <span >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 !

CodePudding user response:

You can use an object as a dictionary to look up your services, or their function, as you could use a dictionary for any kind of mapping from keys to values:

const serviceMap = {
  "solarpanel": SolarPanelService.getSolarPanel,
  "inverters": InverterService.getInverter
}

let lookupFunction = serviceMap[selected]
lookupFunction().subscribe(
 ...
)
  • Related