【问题标题】:Angular 2 pipe modifies original value causing other lists to changeAngular 2管道修改原始值导致其他列表更改
【发布时间】:2016-04-11 13:06:39
【问题描述】:

我遇到了一个奇怪的管道问题,在搜索管道文档时我没有找到解释。

基本上我有一个对对象数组进行排序的管道,问题是如果从同一个源重复更多列表,那么这些列表也会改变,这很奇怪。似乎管道正在修改原始源,然后导致基于它的所有内容发生变化。

如果我再重复一遍:

public options: any[] = [
  {label: 'Item 1'},
  {label: 'Item 3'},
  {label: 'Item 6'},
  {label: 'Item 2'}
];

然后有一个可以通过查询过滤掉的列表:

<div>
  <form-input [(model)]="query" placeholder="Write a search query"></form-input>
  <ul>
    <li *ngFor="#option of options | filterObjects:query">
      {{option.label}}
    </li>
  </ul>
</div>

然后有另一个我使用排序的管道:

<!-- This list's pipe will also affect the list above since they repeat from the same list -->
<div>
  <ul>
    <li *ngFor="#option of options | orderByProperty:'label'">
      {{option.label}}
    </li>
  </ul>
</div>

排序的管道:

import {Pipe} from 'angular2/core';

@Pipe({
  name: 'orderByProperty'
})

export class OrderByPropertyPipe {

  transform(value, args) {

    if (!args[0]) {
      return value;
    }
    else if (value) {

      return value.sort(function(a,b) {
        return (a[args[0]] > b[args[0]]) ? 1 : ((b[args[0]] > a[args[0]]) ? -1 : 0);
      });
    }
  }
}

我将显示两个列表:

  • 项目 1
  • 第 2 项
  • 项目 3
  • 第 6 项

我怎样才能避免这种相当奇怪的行为?

【问题讨论】:

    标签: angular angular2-pipe


    【解决方案1】:

    sort 方法更新当前数组并返回它。不更新原始数组,需要创建一个新数组,例如使用slice 方法。

    您可以尝试以下方法:

    @Pipe({
      name: 'orderByProperty'
    })
    export class OrderByPropertyPipe {
      transform(value, args) {
        var sortedArray = value.slice();
    
        if (!args[0]) {
          return sortedArray;
        } else if (sortedArray) {
          return sortedArray.sort(function(a,b) {
            return (a[args[0]] > b[args[0]]) ? 1 : 
                   ((b[args[0]] > a[args[0]]) ? -1 : 0);
          });
        }
      }
    }
    

    【讨论】:

    • 因此,如果我不想创建原始数组的副本,我必须选择 sort 以外的其他方法,这对我来说似乎很脏,但我想它会做。再次感谢你,直到我们再次见面哈哈。
    • 复制数组引用其中的元素。这些元素不会重复,除非它们是原始类型。如果不创建数组副本,源数组会受到排序的影响...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-01
    • 2017-10-03
    • 1970-01-01
    • 2017-06-30
    • 2021-12-30
    • 2015-12-10
    • 2016-01-24
    相关资源
    最近更新 更多