7

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) 

3 Answers 3

11

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)
Sign up to request clarification or add additional context in comments.

1 Comment

But if you'd change const bar = "bar" to const bar = "b"+"ar", typescript complains (`foo${bar}` cant be used to index obj)
0

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.

Comments

0

sure you can:

class A {
  callFunction(name:string) {
    this[`get${name}`](name);
  }

  getAmount(name: string) {
    alert(name);
  }
}

let a = new A();
a.callFunction('Amount');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.