2017-07-07 122 views
3

如何從函數的回調中訪問變量。我將舉出示例以更直接的問題範圍變量 - 將值分配給變量時出錯

export class FormComponent { 

    public pedidoSoft:PedidoSoft = new PedidoSoft(); 

    getBrandCard(){ 

     PagSeguroDirectPayment.getBrand({ 

      cardBin: this.pedidoSoft.numCard, 
      success: function(response) { 

        this.pedidoSoft.bandCard = response.brand.name; 

      }, 
      error: function(response) { }, 
      complete: function(response) { } 
     }); 

    } 

我收到以下錯誤消息。此錯誤是當this.pedidoSoft.bandCard接收response.brand.name

enter image description here

+0

加上一個使用Ubuntu :) – cgTag

回答

4

的價值不要在打字稿使用function。改爲用()=>{}語句代替。

 success: (response) => { 
       this.pedidoSoft.bandCard = response.brand.name; 
     }, 
     error: (response) => { }, 
     complete: (response) => { } 

當您使用function() {}this不具有持續性,其中作爲()=>{}保持this參考。您可以選擇bind(this)的功能。

+1

您的答案解決了我的問題。我一直試圖弄清楚這個好幾個小時。謝謝。 –