我正在使用 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/