如何从EventEmitter函数返回值? [英] How to return a value from an EventEmitter function?
问题描述
我在core
组件中获得了此功能:
I got this function in my core
component:
isValid(value: any) {
// Do some stuff and return something based on the result
return false;
}
我像这样传递给other-component
:
<other-component (onBeforeAdding)="isValid($event)"></other-component>
在other-component
中,我得到了这个EventEmitter
函数,该函数应在其他事物之前运行,并返回一个值,该值表明该值有效或无效:
And in other-component
I got this EventEmitter
function which should run before other things and return a value stating that a value is valid or not:
@Output() onBeforeAdding: EventEmitter<any> = new EventEmitter();
let isValid = this.onBeforeAdding.emit(value) || true;
if (isValid) {
// Do stuff
}
这里的问题是EventEmitter
函数不能返回值,因为它是异步的(尽管从rc2看来,通过将true传递给new EventEmitter
函数这是可选的吗?即使这样做也无法解决该问题问题).因此,无论函数返回什么结果,isValid
始终为true.
The problem here is that an EventEmitter
function can't return a value since it's asynchronous (although from rc2 it seems that this is optional by passing true to the new EventEmitter
function? Even doing so won't fix this issue however). So isValid
will always be true regardless of what the function returns.
如何从EventEmitter
函数返回值?
推荐答案
简短的答案是您不能使用@Output
来做到这一点,但是您可以使用@Input
做一些非常相似的事情.
The short answer is you can't do this with @Output
, but you can do something very similar with @Input
.
core
组件中的相同功能:
isValid(value: any): boolean {
// Do some stuff and return something based on the result
return false;
}
将函数定义作为@Input
传递到other-component
:
Pass the function definition in to other-component
as an @Input
:
<other-component [onBeforeAddingProcessor]="isValid"></other-component>
在other-component
中:
@Input() onBeforeAddingProcessor: (value: any) => boolean;
ngOnInit() {
// onBeforeAddingProcessor won't be defined in the constructor
let isValid = this.onBeforeAddingProcessor(value);
if (isValid) {
// Do stuff
}
}
访问this
的方法
如果您必须在提供的函数中访问this
,则有必要传递一种已经绑定了此上下文的方法:
Methods accessing this
If you have to access this
in the function you provide, then it's necessary to pass a method which already has the this-context bound:
isValid = (value: any) => {
return this.myService.checkValue(value);
}
否则,Angular会使用组件的this
而不是组件的使用者来调用方法.
关于性能的小提示(尽管未经测试):如果此方法较大且组件的实例计数较高,则应将代码的大部分分解为私有成员函数,然后从原来的位置调用此函数排除在外.原因:上面没有在类的原型上创建函数,但是为组件的每个实例标记了该函数的副本.这样会消耗大量内存,而这些内存很容易避免.
Otherwise Angular calls the method with this
of the component, not the consumer of the component.
Small hint regarding performance (though not tested): if this method is large and the instance-count of the component is high, then you should factor out the bigger parts of the code to a private member function and call this function from where it was factored out. Reason: Above does not create a function on the prototype of the class, but stamps out a copy of this function for each instance of the component. This can consume a lot of memory which can be avoided easily.
这篇关于如何从EventEmitter函数返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!