2017-07-07 176 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

您的答案解决了我的问题。我一直试图弄清楚这个好几个小时。谢谢。 –