在ES6类中设置promise中的属性

sko*_*and 1 javascript angularjs ecmascript-6

我有这个ES6类,在this.categories = data.data执行错误时失败TypeError: Cannot set property 'categories' of undefined.

我认为这是由于this引用了承诺中的上下文.

如何设置this.categories承诺内部?

谢谢.

class NavbarController {
    constructor(bnCategoryService) {
        this.categories = [];    // This is what should be set with data.data.
        this.bnCategoryService = bnCategoryService;
        this.getCategories();
    }

    getCategories() {
        this.bnCategoryService.getCategories()  // Returns a promise
            .success(function(data, status, headers, config) {
                console.log(data.data);
                this.categories = data.data;    // This fails!
            })
            .error(function(data, status, headers, config) {
                console.log('Category service: An error occured getting tags from the server.');
            });
    }
}
Run Code Online (Sandbox Code Playgroud)

Ami*_*mit 6

只需在成功处理程序中使用箭头函数即可获得词法this绑定:

.success((data, status, headers, config) => {
  console.log(data.data);
  this.categories = data.data;    // This won't fail!
})
Run Code Online (Sandbox Code Playgroud)