javascript - Angular4 如何在闭包中调用服务方法

标签 javascript angular

我想在回调方法中使用服务对象。当我在回调方法中使用该服务时,出现未定义的错误。怎么解决呢?

发送.component.ts

import { Component } from '@angular/core';

import { ExampleService } from '../../services/example.service';

@Component({
  selector: 'example',
  templateUrl: './send.component.html',
  styleUrls: ['./send.component.css']
})
export class SendComponent {
  public exampleService = null

  constructor(private service: ExampleService) {
    this.exampleService = service
  }

  submit() {
    function postSendTransactionCallback(result) {
      console.log(this.exampleService); // exampleService is undefined
    }

    this.exampleService.postSendTransaction(this.data, postSendTransactionCallback); // This is no problem
  }
}

最佳答案

定义 postSendTransactionCallback 时使用箭头函数

submit() {
    let postSendTransactionCallback = (result) => {
      console.log(this.exampleService);
    }
    this.exampleService.postSendTransaction(this.data, postSendTransactionCallback);
}
<小时/>

使用 .bind(this) 如下所示,而不更改 postSendTransaction 方法

this.exampleService.postSendTransaction(
  this.data, postSendTransactionCallback.bind(this)
);

关于javascript - Angular4 如何在闭包中调用服务方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46634700/

相关文章:

javascript - 获取所有 id 大于 4 的元素(id 由 string 和 number 组合而成)

angular - npm run 不通过 --configuration 来构建任务

javascript - jquery代理传递参数

Javascript、CanvasRenderingContext2D.drawImage 无法识别图像数据

Angular 发出两次 http 请求

Angular4 Material sidenav 不工作

angular - 使用带有 Angular Material 2 的输入类型文件

angular - 多个路由器 socket 的干净 url Angular

javascript - AJAX 请求未进入就绪状态 4

javascript - 使用 MouseEvent 更改图像时如何避免闪烁?