【问题标题】:Custom Pipe could not be found找不到自定义管道
【发布时间】:2018-03-01 09:23:52
【问题描述】:

我已经建立了一个管道,但我不知道为什么 angular 找不到它。

我的*模块是我的 shared.module

该模块又由 browser.module 或 server.module 集成。

此外,我有一个 user.module 作为最低级别,所有用户的组件都进来。

如果我在 user.module 中定义我的管道,就会找到该管道。

import { ExponentialStrengthPipe } from '../../exponential-strength.pipe';
[...]

@NgModule({
    declarations: [ [...]

        ExponentialStrengthPipe
    ],
    imports: [
        CommonModule,
        HttpModule,
        FormsModule,
        ReactiveFormsModule,
        RouterModule.forChild([...])
    ],

})
export class UserModule {
    constructor(
    ) {
    }

}

如果我将它安装在我的共享中。模块,不再赘述。

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ExponentialStrengthPipe } from './exponential-strength.pipe';
[...]
@NgModule({
    declarations: [
        AppComponent,
[...]
        ExponentialStrengthPipe
    ],

    providers: [
        UserService

    ],
    imports: [
        CommonModule,
        RouterModule.forRoot([
            { path: 'home', component: HomeComponent },
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: '**', component: PageNotFoundComponent },
        ]),
    ],
    exports: [
        ExponentialStrengthPipe
        ]

})
export class AppModuleShared {
    constructor(
    ) {
    }

}

【问题讨论】:

  • 如果你在UserModule之外使用管道,你需要将UserModule添加到你想使用它的模块的imports: [...]中。

标签: angular pipe angular-pipe


【解决方案1】:

如果您想在不同的模块中使用管道,请添加声明管道的模块 imports: [...] 您要重新使用管道的模块,而不是将其添加到模块的declarations: []。 如果您在多个declarations:[] 中添加管道,您将收到一条错误消息,提示您已在多个模块中声明了管道。 所以在这种情况下,您必须在共享模块的declarations: [] 中添加管道,并将共享模块添加到您要使用管道的模块中的imports: [...]。 (例如:用户模块)

【讨论】:

    【解决方案2】:

    您必须在 AppModule 的声明数组中包含您的管道 如果你选择将你的管道注入到一个类中,你必须在你的 NgModule 的 providers 数组中提供它。

    【讨论】: