访问内部函数打字稿内的外部变量

Vin*_*tin 4 javascript typescript

我在函数外部有一个变量,我需要更改该值。我通常使用“this”来访问变量,但在代码的那个点,“this”是不可访问的。

export class GamesDetailPage {

  details : any = {};
  type : String;
  level : Number; 
  cards : any = {}; // THE VARIABLE I WANT TO SET THE VALUE


  constructor(public navCtrl: NavController, public http: HttpClient , private device: Device, private serviceProvider: ServicesProvider,     
                                            public navParams: NavParams
) {
    this.type = navParams.get('gameType');
    this.level = navParams.get('gameLevel');
  }

  ionViewDidLoad() {


    this.getCards();  // WHERE I CALL THE METHOD  
  }


  getCards(){
    var deviceUUID = this.device.uuid;
    var platform =  this.device.platform;
    var cardsReq = {"gameType": this.type ,"gameLevel": this.level};
    var dialog = this.dialogs;

   this.serviceProvider.getCards(deviceUUID, platform, cardsReq)

    .then(function (res){
      this.cards = res;// HERE I WANT TO SET THE VARIABLE BUT "THIS" IS UNDEFINED
    })
    .catch(function(err){
      console.log("Error");
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

voi*_*oid 5

在这里你需要使用ES6 arrow function,因为在早期的(function(){方法中this不引用该类,但在 es6 中它将......

箭头函数表达式的语法比函数表达式更短,并且没有自己的 this

.then( 
(res) => {
      this.cards = res; // Should work now
    }
)
Run Code Online (Sandbox Code Playgroud)


yeh*_*ehe 5

因为外部thisthis函数的遮蔽了。最直接的方法也是推荐的方法是在打字稿中使用箭头函数。

将 lambda 函数更改为:

(res) => {}
Run Code Online (Sandbox Code Playgroud)

另一个旧的解决方案是保存this到临时变量:

that = this
Run Code Online (Sandbox Code Playgroud)

然后在 lambda 函数中访问它。