angular - 如何使用事件发射器调用返回值的函数,并在继续之前等待响应?
问题描述
所以我想从一个触发父组件中的函数的子组件发出一个事件,但我想在继续之前等待从该父函数获得响应。
孩子
@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
通信的情况下,我会坚持使用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>
推荐阅读
- c++ - c++“删除”命令有些奇怪
- laravel - 如何在nuxtjs中获取登录的用户数据?
- javascript - 本地 WordPress 构建的 URL/脚本问题
- c++ - Google Test + VSCode + WINDOWS,如何在window OS中使用gtest?
- python - 如何为我的案例做一个索引增量?
- reactjs - UseEffect - 否则带有大括号会导致错误
- c - c:如何编写c程序来检测和识别读取文件的令牌?
- javascript - 当一个 URL 有参数的时候,为什么我们要把子组件放在一个属性里面
- julia - 在 Julia 中转换字符串和滚动均值的类变异操作
- android - Firestore:多个 whereArrayContains