【发布时间】:2018-07-06 04:23:34
【问题描述】:
我正在将一些代码从 AngularJS 组件移植到 Angular 5 组件中。
我有一个对象数组加载到变量productlist。
在我的旧控制器中,我创建了第二个变量作为空数组,showcaselist。
我在productlist 上运行forEach 循环以查找所有满足条件(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);
}
});
};
}
【问题讨论】:
-
itemsWithSlides = function....语法不正确。 -
@Phax 语法是正确的,只是不寻常。它不是以 ES6 样式声明方法,而是为该属性名称分配一个函数。
-
是的,我们在 ES5 中一直这样做。我还在习惯 ES6/TS。
标签: javascript angular typescript angular-components