通过管道传输到我的自定义过滤器中的对象数组始终显示为零长度

时间:2016-06-09 10:07:43

标签: angular ionic2

我在我的视图中循环遍历一个对象数组(没有管道我显示整个列表):

  <ion-list>
    <ion-item *ngFor= "let category  of (productCategories | onlyhomecategory) " >
      <ion-icon name="arrow-forward" item-right></ion-icon>
      {{category.title}}
    </ion-item>
  </ion-list>

我正在将数组输入名为onlyhomecategory的自定义管道,以过滤掉不具有home属性的任何类别:

import {Injectable, Pipe} from '@angular/core';
@Pipe({
  name: 'onlyhomecategory'

})
@Injectable()
export class OnlyHomeCategories {
  transform(productCategories: any[] , args: any[]) {

    console.log(productCategories.length);  //retuns 0

    //If I hard-code/mock the array, pipe works as expected.

    return productCategories.filter(category => category.home);
  }
}     

这是数组的外观形状:

[
  {
    home: 1,
    title: "Greevy Swaney",
    text: "Find the right area",
  },
  {
    home: 2,
    title: "Taney Wearx",
    text: "Choose the right system",
  },
  {
    title: "Tine rider",
  },
  {
  title: "Shade",
  }
];

这是服务:

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class ProductCategories {
  data: any = null;
  constructor(public http: Http) {}

  load() {
    if (this.data) {
      // already loaded data
      return Promise.resolve(this.data);
    }

    // don't have the data yet
    return new Promise(resolve => {
      this.http.get('https://xxxxxxxxxxxxxxxxxxxxxxxx')
        .map(res => res.json())
        .subscribe(data => {
          this.data = data;
          resolve(this.data);
        });
    });
  }
}

这是视图组件:

import {Page, NavController} from 'ionic-angular';
import {Inject} from '@angular/core'
import {ProductCategories} from '../../providers/product-categories/product-categories'
import {OnlyHomeCategories} from '../../pipes/only-home-categories'

@Page({
  templateUrl: 'build/pages/product-category/product-category.html',
  pipes: [OnlyHomeCategories]
})

export class ProductCategoryPage {
  public productCategories = [];

  constructor(public nav: NavController, private prodCat: ProductCategories)     {

this.prodCat.load()
.then(data => {
  for (var key in data) {
    if (data.hasOwnProperty(key)) {
      this.productCategories.push(data[key]);
    }
  }
  console.log(`this.productCategories.length: ${this.productCategories.length}`); // this return correct length
});

} }

我不确定哪里出错了。如果没有自定义管道,我的视图会显示所有类别,但我似乎无法让管道工作。

2 个答案:

答案 0 :(得分:6)

Angular不会监视阵列内容的更改。因为使用空数组初始化productCategories并稍后将元素添加到同一个数组,更改检测不会检测到更改,也不会再次调用管道。

pure:false

您可以使管道不纯,因此每次更改检测运行时都会调用它,而不仅仅是在管道输入发生变化时

@Pipe({
  name: 'onlyhomecategory',
  pure: false

})
export class OnlyHomeCategories {
  transform(productCategories: any[] , args: any[]) {

    console.log(productCategories.length);  //retuns 0

    return productCategories.filter(category => category.home);
  }
}     

缺点

使管道不纯有性能影响,因为管道被大量调用(每次Angular运行更改检测)。 为了不造成太大的伤害,确保管道不会做昂贵的工作。例如,只要相关输入没有改变,就尝试缓存昂贵计算的结果。您需要自己跟踪以前的和新的值。

不同的对象

您还可以让Angular检测更改,不仅可以添加内容,还可以创建新的 - 不同的数组。

this.prodCat.load()
.then(data => {
  let arr = [];
  for (var key in data) {
    if (data.hasOwnProperty(key)) {
      arr.push(data[key]);
    }
  }
  this.productCategories = arr;
  console.log(`this.productCategories.length: ${this.productCategories.length}`); // this return correct length
});

缺点

如果阵列很大,复制可能很昂贵。

<强>提示

如果修改已包含值的数组,则可以使用slice()创建副本:

this.prodCat.load()
.then(data => {
  for (var key in data) {
    if (data.hasOwnProperty(key)) {
      this.productCategories.push(data[key]);
    }
  }
  this.productCategories = this.productCategories.slice();
  console.log(`this.productCategories.length: ${this.productCategories.length}`); // this return correct length
});

Plunker example

答案 1 :(得分:0)

也许您应该删除args: any[] 请看这个例子:https://angular.io/docs/ts/latest/guide/pipes.html

 import { Pipe, PipeTransform } from '@angular/core';

    import { Flyer } from './heroes';

    @Pipe({ name: 'flyingHeroes' })
    export class FlyingHeroesPipe implements PipeTransform {
      transform(allHeroes:Flyer[]) {
        return allHeroes.filter(hero => hero.canFly);
      }
    }