Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
193
rated 0 times [  197] [ 4]  / answers: 1 / hits: 18238  / 7 Years ago, mon, april 17, 2017, 12:00:00

I am working on Angular2 project in which i need to generate dynamic function which will be able to call the service provided under the service class. The service class has some 10 get functions as the following.



eg:



my service class



import { Injectable } from '@angular/core';

@Injectable()
export class service {

constructor() { }

get function1(){
return 1;
}

get function2(){
return 2;
}

get function2(){
return 3;
}
}


I am trying to create a function which take parameter as the function name and return the corresponding answer.



eg:



my app.component.ts



import { Component} from '@angular/core';
import {service} from ./service;

@Component({
selector: 'app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers : [service]
})

export class AppComponent(){

constructor(private _service:service){}

let one = getVal(function1); /// This should return 1
let two = getVal(function2); /// this should return 2

getVal(val){
return this._service.val; // but i am getting error val not exist on type service
}

}


Is their any solution for this since it will help me to reduce my code and performance.



Thanks in advance


More From » angular

 Answers
201

function1, etc are not just 'get functions' - they are property accessor methods.



Instead, it likely should be



let one = getVal('function1');


and



getVal(val){
return this._service[val];
}

[#58122] Friday, April 14, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jazminkyrap

Total Points: 631
Total Questions: 89
Total Answers: 109

Location: Finland
Member since Fri, Oct 21, 2022
2 Years ago
;