自定义管道返回错误。 :: TypeScript& Angular2

时间:2016-12-14 14:39:34

标签: javascript arrays sorting angular typescript

我最近在我的代码中实现了一个新管道。一切似乎都很好,但在编译应用程序时,我收到了一个错误。这是应用程序的各个部分:

app.component.ts档案

import {SortPipe} from "./sort.pipe";

@Component({
  templateUrl: './app.component.html',
  pipes: [ SortPipe ]
})

sort.pipe.ts档案

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

@Pipe({
  name: 'sort'
})
export class SortPipe implements PipeTransform {

  private ts: number;

  transform(array: Array<any>): Array<any> {
    array.sort((a: any, b: any) => {
      if (a.ts < b.ts) {
        return -1;
      } else if (a.ts > b.ts) {
        return 1;
      } else {
        return 0;
      }
    });
    return array;
  }

}

app.component.html档案

<tr *ngFor="let elem of (_values | sort)">

我收到的错误:

  

[默认] C:\ Users \ app.component.ts:11:2中的错误   类型'{selector:string;模板:任何;风格:任何[];管道:typeof SortPipe []; }'不可分配给   “组件”类型的参数。     对象文字只能指定已知属性,“组件”类型中不存在“管道”。

我真的不知道为什么会发生这种情况,因为我已经阅读了有关此问题的SO的一些信息,并且在大多数情况下解决方案只是将管道名称包含在app.module.ts中。我的模块看起来像(缩小版):

import { SortPipe } from './sort.pipe';

@NgModule({
  declarations: [
     SortPipe
  ] 
})
export class AppModule { }

如果有人知道如何解决或提示,请分享。

2 个答案:

答案 0 :(得分:1)

我认为你不需要为管道制作模块,你可以像这样直接注入你的app.module.ts

import {SortPipe} from "YOURPATH/sort.pipe";

然后将其注入declarations,如下所示:

 declarations: [..., SortPipe]

现在可以在应用程序的任何地方使用它。

正在使用pipe代码:

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

@Pipe({
    name: 'sort'
})

export class SortPipe implements PipeTransform {
    transform(value: any, args: string[]): any {    
        value.sort(function(a, b) {
            return (a.ts > b.ts) ? 1 : ((b.ts > a.ts) ? -1 : 0); });

        return value;
    }
}

答案 1 :(得分:1)

对于较新版本的angular-cli ,您不必在组件内声明管道,甚至不必将其直接导入组件。只需在.module文件中声明您的管道:

import { SortPipe } from 'sort.pipe';

@NgModule({
  declarations: [
    SortPipe
})

如果要按指定属性对对象数组进行排序,请使用以下代码:

sort.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'sort'
})
export class SortPipe implements PipeTransform {

  private name: any;

  transform(array: any, args: any): any {
    array.sort((a: any, b: any) =>
      a.property - b.property     //in your case: a.name - b.name  
    );
    return array;
  }
}

重要提示:请记住,您要对数组进行排序的属性必须是numberany的类型。如果属性是字符串,则必须将类型声明为any

最后一步是将管道与*ngFor循环连接:

<tr *ngFor="let elem of _values | sort">
相关问题