Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic function call for service in typescript

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

like image 443
skid Avatar asked Apr 17 '17 17:04

skid


People also ask

Why can’t you call a function in typescript?

The JavaScript specification states that you cannot have a parameter called this, and so TypeScript uses that syntax space to let you declare the type for this in the function body. This pattern is common with callback-style APIs, where another object typically controls when your function is called.

What is a return type in typescript?

In a return type, this means that the function throws an exception or terminates execution of the program. never also appears when TypeScript determines there’s nothing left in a union.

How do I use generics in typescript?

In TypeScript, generics are used when we want to describe a correspondence between two values. We do this by declaring a type parameter in the function signature: By adding a type parameter Type to this function and using it in two places, we’ve created a link between the input of the function (the array) and the output (the return value).

Can typescript infer the type of a type argument?

Specifying Type Arguments TypeScript can usually infer the intended type arguments in a generic call, but not always. For example, let’s say you wrote a function to combine two arrays: function combine < Type > (arr1: Type [], arr2: Type []): Type [] {


1 Answers

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];
}
like image 50
Estus Flask Avatar answered Oct 12 '22 23:10

Estus Flask