34

我正在开发 angular 2 最终版本。

我已经声明了两个模块主应用程序和一个设置页面

模块正在声明全局管道。该模块还包括设置模块

app.module.ts

@NgModule({
    imports: [BrowserModule, HttpModule, routing, FormsModule, SettingsModule],
    declarations: [AppComponent, JsonStringifyPipe],
    bootstrap: [AppComponent]
})
export class AppModule { }

settings.module.ts

@NgModule({
    imports: [CommonModule, HttpModule, FormsModule, routing],
    declarations: [SettingsComponent],
    exports: [SettingsComponent],
    providers: []
})
export class SettingsModule { }

尝试在设置模块中使用管道时,收到一个错误,即找不到管道。

zone.min.js?cb=bdf3d3f:1 Unhandled Promise rejection: Template parse errors:
The pipe 'jsonStringify' could not be found ("         <td>{{user.name}}</td>
                    <td>{{user.email}}</td>
                    <td>[ERROR ->]{{user | jsonStringify}}</td>
                    <td>{{ user.registered }}</td>
                </tr"): ManageSettingsComponent@44:24 ; Zone: <root> ; Task: Promise.then ; Value: Error: Template parse 

如果我将管道包含在设置模块中,它会抱怨两个模块具有相同的管道。

zone.min.js?cb=bdf3d3f:1 Error: Error: Type JsonStringifyPipe is part of the declarations of 2 modules: SettingsModule and AppModule! Please consider moving JsonStringifyPipe to a higher module that imports SettingsModule and AppModule. You can also create a new NgModule that exports and includes JsonStringifyPipe then import that NgModule in SettingsModule and AppModule.

json-stringify.pipe.ts

@Pipe({name: 'jsonStringify'})
export class JsonStringifyPipe implements PipeTransform {
    transform(object) {
        // Return object as a string
        return JSON.stringify(object);
    }
}

对此有任何想法吗?

4

1 回答 1

85

如果要在不同的模块中使用管道,则将声明管道的模块添加到imports: [...]要重新使用管道的模块中,而不是将其添加到declarations: []多个模块中。

例如:

@NgModule({
    imports: [],
    declarations: [JsonStringifyPipe],
    exports: [JsonStringifyPipe]
})
export class JsonStringifyModule { }
@NgModule({
    imports: [
      BrowserModule, HttpModule, routing, FormsModule, SettingsModule,
      JsonStringifyModule],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule { }
@NgModule({
    imports: [
       CommonModule, HttpModule, FormsModule, routing, 
       JsonStringifyModule],
    declarations: [SettingsComponent],
    exports: [SettingsComponent],
    providers: []
})
export class SettingsModule { }
于 2016-10-13T07:42:56.817 回答