【问题标题】:Service undefined when function called async函数调用异步时服务未定义
【发布时间】:2018-08-09 16:04:24
【问题描述】:

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

  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

如果我调用以下命令而不是 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 而不是超时承诺。

【问题讨论】:

  • 似乎您的服务不在您的组件中。你的组件构造函数是什么样的?
  • @ChrisNewman 服务已正确注入。我可以在一个简单的按钮上直接使用 (click)="sendRequest()" 调用它。但不是来自子组件
  • 尝试在 sendRequest() 的开头添加一个 console.log(this)。您可能会看到“this”指的是您的子组件,它的构造函数中没有服务。

标签: angular promise async-await


【解决方案1】:

您将函数作为输入传递。然后它失去了上下文。 sendRequest 中的 this 不再引用父组件。可能的解决方法是将 lambda 传递给 Input,如下所示:

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

在 html 中:

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

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

<my-child (onEvent)="sendRequest()"></my-child>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-16
    • 2018-09-07
    • 1970-01-01
    • 1970-01-01
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多