首页 > 解决方案 > 如何使用事件发射器调用返回值的函数,并在继续之前等待响应?

问题描述

所以我想从一个触发父组件中的函数的子组件发出一个事件,但我想在继续之前等待从该父函数获得响应。

孩子

@Output() callParentFunction = new EventEmitter<any>();

...

this.callParentFunction.emit();
let tempVal = responseFromParentComponent; //How can I set this value?
//After parent function has returned a response, the next line of code should run
console.log("Response returned");

家长

template: `
    <child-component
      (callParentFunction)="parentFunction($event)"
    >
    </child-component>
  `

...

parentFunction(){
    //This function calls an api, then returns the response
    [API call goes here]
    return response;
}

如何设置此事件发射器?或者有没有办法在没有事件发射器的情况下做到这一点?

标签: angulartypescriptasynchronouseventscomponents

解决方案


parent-child通信的情况下,我会坚持使用setter以便在属性更改时做一些事情。

child.component.ts

@Input()
set response (v: any) {
 // Do some logic here
}

@Output() 
callParentFunction = new EventEmitter<any>();

doStuff () {
 this.callParentFunction.emit();
}

父组件.ts

public response$: Observable<IResponse | null> = of(null);

parentFunction(){
    this.response$ = this.http.get(/* ... */)
}

父组件.html

<child-component
  [response]="response$ | async" 
 (callParentFunction)="parentFunction($event)"
></child-component>

推荐阅读