У меня есть этот класс ES6, который не работает, когда this.categories = data.data
выполнен с ошибкой TypeError: Cannot set property 'categories' of undefined
.Установка свойства из обещания в классе ES6
Я думаю, что это связано с 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.');
});
}
}
Что такое '.success'? какой API? и почему вы отметили ES6? – Amit
(1) .success - это обещание от углового объекта $ http, (2) API - это мои сайты api, где data.data - это массив музыкальных треков, (3) Это класс, поэтому он использует ES6-синтаксис – skovmand
'success' - это просто сахар для' then' с некоторым предварительным анализом http-response –