I am working on Ionic2 app. I am calling a function from a a Page. Is it possible that I use a variable name in function call. e.g.
original code: this._userDataService.getGrandQuestionsFromServer(this.passedId, newLevel)
expected code::
this._userDataService.get`${this.questionModuleName}`QuestionsFromServer(this.passedId, newLevel)
You should be able to achieve this with bracket notation. Here is a working example:
const obj = {
foobar(arg) {
console.log(arg);
}
};
const bar = "bar";
obj[`foo${bar}`]("It works!");
In your code, please try this:
this._userDataService[`get${this.questionModuleName}QuestionsFromServer`](this.passedId, newLevel)
There is a feature called Tagged template literals
A more advanced form of template literals are tagged template literals. Tags allow you to parse template literals with a function. The first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions. In the end, your function can return your manipulated string (or it can return something completely different as described in the next example). The name of the function used for the tag can be named whatever you want. MDN - Template strings
You can use it to preprocess the string and generate the function call you want.
sure you can:
class A {
callFunction(name:string) {
this[`get${name}`](name);
}
getAmount(name: string) {
alert(name);
}
}
let a = new A();
a.callFunction('Amount');