因此,我想从子组件中发出一个事件,该事件会触发父组件中的功能,但是我想等待继续之前从该父函数获得响应。
儿童
@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;
}
如何设置此事件发射器?还是有没有事件发射器的方法?
parent-child
交流的情况下,我会坚持使用setters,以便在属性更改时做一些事情。
@Input()
set response (v: any) {
// Do some logic here
}
@Output()
callParentFunction = new EventEmitter<any>();
doStuff () {
this.callParentFunction.emit();
}
public response$: Observable<IResponse | null> = of(null);
parentFunction(){
this.response$ = this.http.get(/* ... */)
}
<child-component
[response]="response$ | async"
(callParentFunction)="parentFunction($event)"
></child-component>
我偏爱集中式事件服务。本文对此进行了很好的描述。https://dev.to/jwp/the-angular-event-service-ech