ski*_*kid 5 javascript typescript angular
我正在 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;
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试创建一个将参数作为函数名称并返回相应答案的函数。
例如:
我的 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
}
}
Run Code Online (Sandbox Code Playgroud)
他们是否对此有任何解决方案,因为它将帮助我减少我的代码和性能。
提前致谢
function1等不仅仅是“获取函数”——它们是属性访问器方法。
相反,它可能应该是
let one = getVal('function1');
Run Code Online (Sandbox Code Playgroud)
和
getVal(val){
return this._service[val];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12382 次 |
| 最近记录: |