我正在从事 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
}
}
他们是否对此有任何解决方案,因为它会帮助我减少代码和性能。
提前致谢
最佳答案
function1
等不仅仅是“获取函数”——它们是属性访问器方法。
相反,它可能应该是
let one = getVal('function1');
和
getVal(val){
return this._service[val];
}
关于javascript - typescript 中服务的动态函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43456415/