我想在回调方法中使用服务对象。当我在回调方法中使用该服务时,出现未定义的错误。怎么解决呢?
发送.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/