2017-10-08 67 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); // 
    }); 
    } 
相關問題