【发布时间】: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