typescript Angular 2:从字符串名称调用函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42108530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 2: Call function from a string name
提问by Lunin Roman
I'm not sure is it question related to Angular 2 or more to Typescript itself. But anyway, I have a component which emits object
我不确定它是否与 Angular 2 或更多与 Typescript 本身有关。但无论如何,我有一个发出对象的组件
<grid" (gridButtonClickEvent)="gridEvent($event)"></grid>
Here is how I catching the event
这是我如何捕捉事件
private gridEvent(event) {
console.log(event);
}
Here is the the event format of what I'm getting.
这是我得到的事件格式。
{Key: value}
So basically it's a simple object.
I want to call a function with name Key
and pass a value
as an argument, how is it possible? The object Key
would be different, but I know all possible variants and already registered function in my component.
所以基本上它是一个简单的对象。我想调用一个带有名称的函数Key
并将 avalue
作为参数传递,这怎么可能?该对象Key
会有所不同,但我知道所有可能的变体和已在我的组件中注册的功能。
private Key() {}
I was trying something like this
我正在尝试这样的事情
private gridEvent(event) {
let eventName = Object.keys(event)[0];
window[eventName]();
}
But it says
但它说
window[eventName] is not a function
回答by Seid Mehmedovic
Try this:
试试这个:
private gridEvent(event) {
let methodName = Object.keys(event)[0];
if(this[methodName]) {
// method exists in the component
let param = event[methodName];
this[methodName](param); // call it
}
}
More intuitive way would be to construct your emitting object as:
更直观的方法是将您的发射对象构造为:
{ methodName: 'method1', methodParam: someValue }
Then in the component:
然后在组件中:
private gridEvent(event) {
let methodName = event.methodName;
if(this[methodName]) {
// method exists on the component
let param = event.methodParam;
this[methodName](param); // call it
}
}
However, I'd personally avoid doing it this way if not really necessary. Rather emit an action that should be triggered and then do some switch statement to call the appropriate method instead. A dumber approach, but easier to reason about I'd say.
但是,如果不是真的有必要,我个人会避免这样做。而是发出一个应该被触发的动作,然后执行一些 switch 语句来调用适当的方法。一种更愚蠢的方法,但我会说更容易推理。