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

标签 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)">

我收到的错误:

ERROR in [default] C:\Users\app.component.ts:11:2 Argument of type '{ selector: string; template: any; styles: any[]; pipes: typeof SortPipe[]; }' is not assignable to parameter of type 'Component'. Object literal may only specify known properties, and 'pipes' does not exist in type 'Component'.

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

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

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

如果有人有任何解决此问题的想法或任何提示,请分享。

最佳答案

对于较新版本的 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">

关于javascript - 自定义管道返回错误。::TypeScript & Angular2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41145287/

相关文章:

javascript - 添加新行不起作用?

javascript - 是否可以仅从本地网络显示 WebRTC 对等点?

javascript - 在数组字符串中搜索一个搜索词

Javascript函数clearInterval不停止动画

javascript - 主要浏览器允许的 cookie 数量和大小是多少?

javascript - 为什么代码停止检查是否是数组?

ios - 如何搜索对象数组并仅返回 objective-c 中具有特定 uid 的对象

python - "Order By" Elasticsearch

java - 仅使用带有 lambda 的 Collection.sort() 对对象列表进行排序

javascript - 将整数数组排序为奇数,然后是偶数