【问题标题】:How can I access the properties of a JavaScript class from inside a promise? (Using ES6 not Self) [duplicate]如何从 Promise 中访问 JavaScript 类的属性? (使用 ES6 而不是 Self)[重复]
【发布时间】:2016-06-07 15:23:15
【问题描述】:

我正在使用 ES6 类来创建一个角度控制器。我正在尝试使用承诺来加载我的产品。当我调用 getProducts 时,结果会返回我需要的数据,但是 this.products = results 中的 this 是未定义的,我得到“无法设置未定义的属性‘产品’”。如何从 then 内部访问属性?

export class ProductController {  
  constructor (Product) {
    'ngInject';

    this.ProductService = Product;
    this.products = [];    
    this.getProducts();
  }

    getProducts() {
      this.ProductService
        .find()
        .$promise
        .then(function (results) {
            this.products = results;
        }, function (results) {
            console.log(results);
        });
  }
}

【问题讨论】:

  • 一种方法是使用箭头=>函数...所以.then(results => this.products = results, results => console.log(results));
  • 我尝试替换函数(结果){ this.products = results; } with (results) => this.products = 结果没有运气
  • 箭头函数是这里的方法。但请注意,您实际上不应该将异步接收的数据写入实例属性 - 只需将 Promise 本身存储在属性中,许多事情会变得更容易。
  • 那么您的问题在其他地方 - 您的控制台是否有任何错误?
  • @Bergi - 这种模式在 angularjs 中似乎很常见

标签: javascript angularjs promise ecmascript-6


【解决方案1】:

免责声明:我对 ES6 不是很熟悉,所以这可能是一种过时的方法。

我避免this 出现问题的一般方法是重命名它:

getProducts() {
  let self = this
  this.ProductService
    .find()
    .$promise
    .then(function (results) {
        self.products = results;
    }, function (results) {
        console.log(results);
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 2016-06-10
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    • 2016-05-22
    • 1970-01-01
    相关资源
    最近更新 更多