我如何使用事件发射器来调用返回值的函数,并在继续之前等待响应?

问题描述 投票:0回答:2

因此,我想从子组件中发出一个事件,该事件会触发父组件中的功能,但是我想等待继续之前从该父函数获得响应。

儿童

@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;
}

如何设置此事件发射器?还是有没有事件发射器的方法?

angular typescript asynchronous events components
2个回答
1
投票

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

child.component.ts

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

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

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

parent.component.ts

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

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

parent.component.html

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

1
投票

我偏爱集中式事件服务。本文对此进行了很好的描述。https://dev.to/jwp/the-angular-event-service-ech

© www.soinside.com 2019 - 2024. All rights reserved.