打字稿中服务的动态函数调用

新手上路,请多包涵

我正在从事 Angular2 项目,在该项目中我需要生成能够调用服务类下提供的服务的动态函数。服务类有如下 10 个 get 函数。

例如:

我的服务等级

import { Injectable } from '@angular/core';

@Injectable()
export class service {

  constructor() { }

  get function1(){
    return 1;
  }

  get function2(){
    return 2;
  }

  get function2(){
    return 3;
  }
}

我正在尝试创建一个将参数作为函数名称并返回相应答案的函数。

例如:

我的 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
    }

}

他们是否对此有任何解决方案,因为它将帮助我减少代码和性能。

提前致谢

原文由 skid 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 388
2 个回答

function1 等不仅仅是“获取函数”——它们是属性访问器方法。

相反,它可能应该是

let one = getVal('function1');

getVal(val){
 return this._service[val];
}

原文由 Estus Flask 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以使用“any”来绕过 TypeScript 强类型检查。

返回(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"));

原文由 tmorell 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题