ES6 and variable scope inside a promise

后端 未结 2 1172
执笔经年
执笔经年 2021-01-19 01:04

Not sure what I\'m missing here.

I need to get the output of data into this.contact. Right now, I\'m using a static class variable, but it

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-19 01:14

    You need to do two things. First, use an arrow function, and second, use `this.contact = data;

    activate(id) {
      this.id = id;
      return dpd.contacts.get(id).then(data => {
        console.log(data);
        this.contact = data;
      });
    }
    

    You use an arrow function because it deals with JavaScript's "this" issue, where this refers to the lexical scope of the function, and not the object you're currently in. Using an arrow function makes sure that this outside the arrow function is the same as this inside the arrow function.

    You need to use this.contact because contact is an instance property of the class.

提交回复
热议问题