Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
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

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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];
}
about 4 years ago · Santiago Trujillo Relatório

0

A little difficult to to tell what you're asking, but this may help.

class MyService {
 get function1() {
   return 1;
 }
  get function2() {
   return 2;
 }
  get function3() {
   return 3;
 }
}

const service = new MyService();

const getValFactory = service => name => service[name];
const getVal = getValFactory(service);

// Use strings, not unquoted function names.
console.log(getVal('function1'));
console.log(getVal('function2'));
console.log(getVal('function3'));

about 4 years ago · Santiago Trujillo Relatório

0

You can use "any" to bypass the TypeScript strong typing checking.

return (this.service as any)[val]

class Service {
	constructor() {}
	get function1() {
		return 1;
	}
	get function2() {
		return 2;
	}
	get function3() {
		return 3;
	}
}

class AppComponent {
	constructor(private service: Service) {}
	getVal(val: string) {
		return (this.service as any)[val];
	}
}

const service = new Service();
const app = new AppComponent(service);
console.log(app.getVal("function1"));
console.log(app.getVal("function2"));
console.log(app.getVal("function3"));

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda