我想在回调方法中使用服务对象。当我在回调方法中使用服务时,我得到未定义的错误。我该如何解决?
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
}
}
答案 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); //
});
}