2017-10-08 31 views
0

我想在回调方法中使用服务对象。当我在回调方法中使用服务时出现未定义的错误。我该如何解决它?Angular4我怎样才能调用封闭的服务方法

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

回答

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) 
); 
+0

谢谢。你救了我。我会在2分钟内接受你的回答。 – zono

1

用户箭头的功能,因为javascript arrow(=>) function绑定与它的范围定义它:

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