2017-01-27 37 views
1

我想用管道按照提供的here对一些数据进行排序。如何在离子2中使用管道(发布v2.2.1)

上面看起来与angular documentation一致,即我们有以下的进口和类定义:

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

@Pipe({name: 'exponentialStrength'}) 
export class ExponentialStrengthPipe implements PipeTransform { 
    transform(value: number, exponent: string): number { 
    let exp = parseFloat(exponent); 
    return Math.pow(value, isNaN(exp) ? 1 : exp); 
    } 
} 

所以,在上面我们从PipePipeTransform导入,然后我们从PipeTransform派生我们班。

使用离子发生器,例如ionic g pipe testPipe我注意到不同的进口,并且还没有实现PipeTransform

@Pipe({ 
    name: 'test-pipe' 
}) 
@Injectable() 
export class TestPipe { 
    transform(value, args) { 
    value = value + ''; // make sure it's a string 
    return value.toLowerCase(); 
    } 
} 

所以它不会延伸PipeTransform?无论如何,继续下去,我试图使用它,所以我尝试将它添加到我的组件。

import { TestPipe } from '../../pipes/test-pipe'; 

@Component({ 
    pipes:[TestPipe], 
    selector: 'my-page', 

,我得到这个打字稿错误:

[ts] Argument of type '{ pipes: typeof TestPipe[]; selector: string; 
templateUrl: string; animations: AnimationEntryM...' is not assignable 
to parameter of type 'Component'. 
Object literal may only specify known properties, and 'pipes' does not 
exist in type 'Component'.` 

任何一个有什么想法吗?管道的doco似乎不匹配。

回答

6

在发布版本的Angular 2中,@Component decorator不包含pipes属性。相反,你应该自定义管道添加到您的应用程序或功能NgModuledeclarations

import { TestPipe } from '... pipes/test-pipe'; 

@NgModule({ 
    declarations: [ 
    TestPipe, 
    ... 
    ], 
    ... 
}) 
class AppModule {} 

有了它添加到NgModuledeclarations没有必要将其导入到你的组件模块;只需在组件的模板中使用它。

+0

这工作100%!所以Angular doco的活动有点过时了。现在只是为了让排序管工作(它被调用,但我的物品没有排序 - 但这是另一个问题) – peterc

+0

你,我喜欢你! – pcarrara