如何从EventEmitter函数返回值?

Chr*_*odz 41 angular

我在我的core组件中有这个功能:

 isValid(value: any) {

   // Do some stuff and return something based on the result

   return false;
 }
Run Code Online (Sandbox Code Playgroud)

我传到other-component这样的:

<other-component (onBeforeAdding)="isValid($event)"></other-component>
Run Code Online (Sandbox Code Playgroud)

并且other-component我得到了这个EventEmitter函数,该函数应该在其他事情之前运行并返回一个值,表明值是否有效:

 @Output() onBeforeAdding: EventEmitter<any> = new EventEmitter();

 let isValid = this.onBeforeAdding.emit(value) || true;

 if (isValid) {

   // Do stuff
 }
Run Code Online (Sandbox Code Playgroud)

这里的问题是EventEmitter函数不能返回一个值,因为它是异步的(虽然从rc2来看,这似乎是可选的,通过将true传递给new EventEmitter函数?即使这样做也不会解决这个问题).所以,isValid永远是真实的,无论该函数返回什么.

如何从EventEmitter函数中返回值?

Isa*_*aac 69

简短的回答是你无法做到这一点@Output,但你可以做一些非常相似的事情@Input.

core组件中的功能相同:

isValid(value: any): boolean {
  // Do some stuff and return something based on the result
  return false;
}
Run Code Online (Sandbox Code Playgroud)

在传递给函数的定义other-component为@Input:

<other-component [onBeforeAddingProcessor]="isValid"></other-component>
Run Code Online (Sandbox Code Playgroud)

在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
  }
}
Run Code Online (Sandbox Code Playgroud)

方法访问 this

如果您必须访问this您提供的函数,则必须传递已具有此上下文绑定的方法:

isValid = (value: any) => {
  return this.myService.checkValue(value);
}
Run Code Online (Sandbox Code Playgroud)

否则,Angular会调用this组件的方法,而不是组件的使用者.关于性能的小提示(虽然未经过测试):如果此方法很大且组件的实例数很高,那么您应该将代码的较大部分分解为私有成员函数,并从它的位置调用此函数因素考虑在内.原因:上面没有在类的原型上创建函数,但为组件的每个实例标记了此函数的副本.这可能会消耗大量内存,这很容易避免.

  • 喜欢堆栈溢出答案的前几句话对我有用,当一个无关的问题出现时,同样的答案甚至会预测并回答这个问题; 感谢@hgoebl"如果你必须在你提供的功能中访问它".我做!`this`有我叫的服务! (4认同)
  • ...在阅读该问题的答案时,我学到了一些新东西(当然暗示在 hgoebl 的编辑中);lambda 又名“胖箭头”[将绑定 `this`,因此它无法更改。](https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html) (2认同)