Angular 2 - Pipe reuse in multiple modules - error

2019-02-01 23:27发布

问题:

Im working on angular 2 final release.

I have declared two modules: main app and one for the settings page.

The main module is declaring globally pipes. This module is also including the settings module.

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 { }

When trying to use the pipe in the settings module I'm getting an error that the pipe could not be found.

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 

If I include the pipe into the settings module it complains about the two modules having same pipe.

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);
    }
}

Any idea about this?

回答1:

If you want to use the pipe in a different module, then add the module where the pipe is declared to imports: [...] of the module where you want to re-use the pipe, instead of adding it to declarations: [] of multiple modules.

For example:

@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 { }