【问题标题】:How to get the return of a async function called by an event in html?如何获得由html中的事件调用的异步函数的返回?
【发布时间】:2021-04-13 05:12:26
【问题描述】:

我正在开发一个 Angular 应用程序,它有一个带有点击事件的按钮。 但是该方法是使用订阅异步的。 我需要返回调用另一个类中的另一个方法。

我需要在 listItems.getData() 完成后调用 player.start(),问题是 getData() 是在 html 中调用,我需要捕获此方法的终止事件以触发 start() 方法。

播放器.html:

<button color="primary" (click)="listItems.getData()" ...

ListItems.ts:

export class ListItems {
    ...
    getData() {
        /**
        ** I call getData() in Html context, making it impossible to 
        ** get the result inside a class in typescript
        **/
        ...
        return this.http.get(url).subscribe(res => {
            this.data = res;
        }
    }
}

player.ts:

export class Player {
    constructor(public listItems: ListItems) {
    }
    start() {
        /**
        ** start method only can be called after listItems.data get data
        **/
        let alldata = this.listItems.data.replace('\n', '');
        ....
    }
    ....
}

【问题讨论】:

    标签: angular typescript asynchronous async-await


    【解决方案1】:

    当 http 请求完成时,ListItems 可以向其父组件发出事件(例如 onData)。然后 Player 组件可以将“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;
      }
    }
    

    查看工作玩具示例:https://codesandbox.io/s/angular-angular?fontsize=14&hidenavigation=1&theme=dark

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-27
      • 2018-01-03
      • 2020-12-18
      • 2018-06-22
      • 1970-01-01
      • 2022-09-22
      • 1970-01-01
      • 2021-06-13
      相关资源
      最近更新 更多