Angular 5: доступ к переменной в компоненте из цикла
Я портирую некоторый код из компонента AngularJS в компонент Angular 5.
У меня есть массив объектов, загруженных в переменную productlist
,
В моем старом контроллере я создал вторую переменную как пустой массив, showcaselist
,
Я бегу forEach
петля на productlist
найти все предметы, которые соответствуют условию (item.acf.product_slide.length > 0
) и подтолкнуть их в showcaselist
, Затем я отображаю эти элементы в своем шаблоне.
Вход в консоль показывает, что данные поступают, и if
оператор работает, но я получаю консольную ошибку:TypeError: undefined is not an object (evaluating 'this.showcaselist')
Вот весь компонент:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'pb-ds-showcaseindex',
templateUrl: './showcaseindex.component.html'
})
export class ShowcaseindexComponent implements OnInit {
productlist;
showcaselist = [];
constructor(private _route: ActivatedRoute) { }
ngOnInit() {
this.productlist = this._route.snapshot.data.showcases;
this.itemsWithSlides();
}
itemsWithSlides = function () {
this.productlist.forEach(function (item) {
if (item.acf.product_slide.length > 0) {
this.showcaselist.push(item);
}
});
};
}
3 ответа
Попробуйте вместо этого использовать функцию со стрелкой - текущая функция создает новую this
это относится к другому объекту.
itemsWithSlides = () => {
this.productlist.forEach((item) => {
if (item.acf.product_slide.length > 0) {
this.showcaselist.push(item);
}
});
};
Вы можете сократить все это с помощью filter()
функция
export class ShowcaseindexComponent implements OnInit {
productlist;
showcaselist = [];
constructor(private _route: ActivatedRoute) { }
ngOnInit() {
this.productlist = this._route.snapshot.data.showcases;
this.showcaseList = this.productList.filter(item => item.acf.product_slide.length > 0);
}
}
Попробуй это:
ngOnInit() {
this.productlist = this._route.snapshot.data.showcases;
this.itemsWithSlides(this.productList);
}
private itemsWithSlides(productList) {
if (productList) {
productList.forEach(item => {
if (item && item.acf.product_slide.length > 0) {
this.showcaseList.push(item);
}
});
}
}