Angular4如何在闭包中调用service方法

时间:2017-10-08 18:38:10

标签: javascript angular

我想在回调方法中使用服务对象。当我在回调方法中使用服务时,我得到未定义的错误。我该如何解决?

send.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
  }
}

2 个答案:

答案 0 :(得分:1)

在定义function

时使用箭头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)
);

答案 1 :(得分:1)

用户箭头函数,因为javascript arrow(=>) function将范围与定义它的范围绑定在一起:

 submit() {
    this.exampleService.postSendTransaction(this.data, (result) => {
      console.log(this.exampleService); // 
    }); 
  }