【问题标题】:Angular 2 custom pipe not found找不到Angular 2自定义管道
【发布时间】:2017-04-16 07:51:53
【问题描述】:

起初:Angular2: custom pipe could not be found 无论如何这对我没有帮助.. 我有以下问题:

管道:

import { Pipe, PipeTransform } from "@angular/core";
import { DecimalPipe} from "@angular/common"; 

@Pipe({
    name: "ToNumberPipe"
})
export class ToNumberPipe extends DecimalPipe implements PipeTransform  {
    // this allows to pass strings in decimalpipes as well and do nothing if it NAN
    public transform(value: string, args: string): any {
        const retNumber = Number(value);
        if (isNaN(retNumber)) {
            return value;
        }
        return super.transform(value, args);
    }
}

应用程序:模块

@NgModule(
    {
        // all components, pipes and directive which are using this module
        declarations: [AppComponent, ... all Components go here],
        // All modules like forms or http
        imports: [...., MainPipeModule],
        // all services and other providers
        providers: [...all services go here],
        bootstrap: [AppComponent]
    }
)
export class AppModule {
}

管道模块

import { NgModule } from "@angular/core";
import {CommonModule} from "@angular/common";

import {ToNumberPipe} from "./shared/pipes/customNumber.pipe";
@NgModule(
    {
        // all components, pipes and directive which are using this module
        declarations: [ToNumberPipe],
        imports: [CommonModule],
        exports: [ToNumberPipe]
    })
export class MainPipeModule {
}

HTML代码

<span [ngClass]="getClass(rowValue)" class="badge isLink" (click)="selectTask(rowValue.taskId)">{{rowValue.value | ToNumberPipe : "1.0-4"}}</span>

我尝试将管道直接添加到 app.module,但结果相同...

zone.js:1 Unhandled Promise rejection: Template parse errors:
The pipe 'ToNumberPipe' could not be found

我还尝试删除参数并添加一个简单的管道......总是同样的错误

Angular 2 版本:2.2.4

【问题讨论】:

  • 哪个组件包含使用管道的代码? NgModule 这个组件属于什么?
  • 所有组件都在同一个 app.module 文件中。在我把它分成一些模块之前,我认为不同的模块可能有问题。但是将应用程序的所有部分移动到一个模块中并没有帮助..

标签: angular


【解决方案1】:

你必须至少使用v2.3.0-rc.0

此版本包含以下功能:core: properly support inheritance

我猜你的 Pipe 被正确包含等等,但是那些装饰器(例如你的名字)没有正确发布..

【讨论】: