Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
Llamada de servicio de función dinámica en mecanografiado

Estoy trabajando en el proyecto Angular2 en el que necesito generar una función dinámica que podrá llamar al servicio proporcionado bajo la clase de servicio. La clase de servicio tiene unas 10 funciones de obtención como las siguientes.

p.ej:

mi clase de servicio

 import { Injectable } from '@angular/core'; @Injectable() export class service { constructor() { } get function1(){ return 1; } get function2(){ return 2; } get function2(){ return 3; } }

Estoy tratando de crear una función que tome el parámetro como el nombre de la función y devuelva la respuesta correspondiente.

p.ej:

mi aplicación.componente.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 } }

¿Hay alguna solución para esto, ya que me ayudará a reducir mi código y rendimiento?

Gracias por adelantado

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

function1 , etc. no son solo 'obtener funciones', son métodos de acceso a propiedades.

En cambio, probablemente debería ser

 let one = getVal('function1');

y

 getVal(val){ return this._service[val]; }
about 4 years ago · Santiago Trujillo Report

0

Es un poco difícil decir lo que estás preguntando, pero esto puede ayudar.

 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 Report

0

Puede usar "cualquiera" para omitir la verificación de escritura fuerte de TypeScript.

return (este.servicio como cualquiera)[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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!