当函数调用async时,服务未定义

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

在一个组件中,我有一个调用服务的简单方法:

  sendRequest() {
    this.myService
      .doStuff()
      .then((res) => { ... }
  }

这个doStuff()方法是http.post转换toPromise()

  doStuff(): Promise<any> {
    return this.http.post(somewhere).toPromise();
  }

在这个组件中我有另一个子组件接收函数@Input()(它是一个简单的按钮)

<my-child [callback]="sendRequest"></my-child>

当我点击这个按钮时,我得到一个

找不到属性doStuff的undefined

如果我调用以下代替doStuff,我会得到预期的行为:

  async testMe() {
    console.log("wait 5 sec");
    await new Promise(res => setTimeout(res, 5000));
    console.log("finished");
  }

我基本上试图实现这个:

https://stackblitz.com/edit/angular-ypqkcf-eduhze?file=app%2Fprogress-spinner-overview-example.ts

使用http.post而不是超时承诺。

angular promise async-await
1个回答
2
投票

您将该函数作为输入传递。然后它失去了背景。 this中的sendRequest不再指父母成分。可能的解决方法是将lambda传递给Input,如下所示:

const lambda = () => this.sendRequest()

并在HTML中:

<my-child [callback]="lambda"></my-child>

顺便把回调作为Input传递给子组件并不是一个好主意。假设您传递的函数由子组件在某个事件上调用,只需使用子组件中的Output发出该事件,并使用Angular模板语法订阅它:

<my-child (onEvent)="sendRequest()"></my-child>
© www.soinside.com 2019 - 2024. All rights reserved.