【问题标题】:Angular 5: accessing variable in component from loopAngular 5:从循环访问组件中的变量
【发布时间】: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


【解决方案1】:

您可以使用 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);
  }
}

【讨论】:

【解决方案2】:

试试这个:

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);
      }
    });
  }
}

【讨论】:

    【解决方案3】:

    尝试改用箭头函数 - 当前函数正在创建一个新的 this 引用不同的对象。

      itemsWithSlides = () => {
        this.productlist.forEach((item) => {
          if (item.acf.product_slide.length > 0) {
            this.showcaselist.push(item);
          }
        });
      };
    

    【讨论】:

    • 谢谢。箭头函数对我来说是新的。不过,我认为它与“this”有关。
    猜你喜欢
    • 2018-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-01
    相关资源
    最近更新 更多