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
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]; }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'));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"));