javascript - 如何从 Promise 内部访问 JavaScript 类的属性? (使用ES6而不是Self)

标签 javascript angularjs promise ecmascript-6

我正在使用 ES6 类来创建 Angular Controller 。我正在尝试使用 promise 来加载我的产品。当我调用 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);
        });
  }
}

最佳答案

Disclaimer: I'm not incredibly familiar with ES6, so this may be an outdated approach.

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

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

关于javascript - 如何从 Promise 内部访问 JavaScript 类的属性? (使用ES6而不是Self),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35617370/

相关文章:

javascript - 响应式 jQuery Canvas , Canvas 背景在窗口调整大小时消失

javascript - 更改传单中激活鼠标悬停事件的阈值

javascript - 如何使用隔离范围提高 Angular Directive(指令)中双向绑定(bind)的性能?

javascript - 异步等待获取未定义。怎么处理?

xml-parsing - Bluebird promise `promisifyAll` 不起作用 - 无法读取属性 `then`

Javascript 比较运算符字符串和数字

javascript - 使用 UI Router 进行分页时如何更改 URL?

javascript - JS/ANGULAR 使用 var 的值作为另一个对象的键

javascript - JS promise : What is the difference between then and catch

javascript - Rails 5,Cocoon Gem - 嵌套形式中的嵌套形式