Angular 如何获得html中事件调用的异步函数的返回?
我正在开发一个Angular应用程序,它有一个带有点击事件的按钮。 但是使用subscribe的方法是异步的。 我需要得到调用另一个类中的另一个方法的返回 我需要在listItems.getData()完成后调用player.start(),问题是html中调用了getData(),我需要捕获此方法的终止事件以触发start()方法 player.html:Angular 如何获得html中事件调用的异步函数的返回?,angular,typescript,asynchronous,async-await,Angular,Typescript,Asynchronous,Async Await,我正在开发一个Angular应用程序,它有一个带有点击事件的按钮。 但是使用subscribe的方法是异步的。 我需要得到调用另一个类中的另一个方法的返回 我需要在listItems.getData()完成后调用player.start(),问题是html中调用了getData(),我需要捕获此方法的终止事件以触发start()方法 player.html: { 这个数据=res; } } } player.ts: 导出类播放器{ 构造函数(公共列表项:列表项){ } 开始(){ /** **
{
这个数据=res;
}
}
}
player.ts:
导出类播放器{
构造函数(公共列表项:列表项){
}
开始(){
/**
**只能在listItems.data获取数据之后调用start方法
**/
让alldata=this.listItems.data.replace('\n','');
....
}
....
}
当http请求完成时,ListItems可以向其父组件发出事件(例如onData)。然后播放器组件可以将“start()”方法调用绑定到ListItem组件的“onData”事件
import { Component, EventEmitter, Output } from "@angular/core";
@Component({
selector: "list-items",
template: `
<h2>Items:</h2>
<ul>
<li *ngFor="let item of data">{{ item }}</li>
</ul>
<button (click)="getData()">Get Data</button>
`,
})
export class ListItems {
@Output()
dataReceived = new EventEmitter<void>();
data: string[] = [];
getData() {
setTimeout(() => {
// simulate http request
this.data = ["hello", "world"];
this.dataReceived.emit();
}, 2000);
}
}
@Component({
selector: "app-root",
template: `
<h1>Player</h1>
<list-items (dataReceived)="start()"></list-items>
<h2>start() invoked: {{ invoked }} </h2>
`,
styleUrls: ["./app.component.css"]
})
export class Player {
title = "CodeSandbox";
invoked: boolean = false;
start() {
this.invoked = true;
}
}
import{Component,EventEmitter,Output}来自“@angular/core”;
@组成部分({
选择器:“列出项目”,
模板:`
项目:
- {{item}
获取数据
`,
})
导出类列表项{
@输出()
dataReceived=新的EventEmitter();
数据:字符串[]=[];
getData(){
设置超时(()=>{
//模拟http请求
this.data=[“你好”,“世界”];
this.dataReceived.emit();
}, 2000);
}
}
@组成部分({
选择器:“应用程序根”,
模板:`
玩家
调用的start()为:{{invoked}
`,
样式URL:[“/app.component.css”]
})
出口级玩家{
title=“CodeSandbox”;
调用:boolean=false;
开始(){
this.invoked=true;
}
}
请参见工作玩具示例: