首页 文章

自定义管道返回错误 . :: TypeScript和Angular2

提问于
浏览
0

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

app.component.ts file:

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

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

sort.pipe.ts file:

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 file:

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

Error which I'm receiving:

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

我没有阅读有关此问题的SO的一些信息,大多数情况下解决方案只是将管道名称包含在 app.module.ts 中 . 我的模块看起来像(缩小版):

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

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

如果有人有任何想法如何解决或任何提示,请分享 .

2 回答

  • 1

    对于较新版本的angular-cli you don't have to declare pipes inside the component or even import it directly to the component . 只需在 .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;
      }
    }
    

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

    最后一步是使用 *ngFor 循环连接管道:

    <tr *ngFor="let elem of _values | sort">
    
  • 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;
        }
    }
    

相关问题