Angular 2 - Повторное использование труб в нескольких модулях - ошибка не найдена или дублируется определение

Im работает над выпуском 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"): [email protected]: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);
    }
}

Есть ли идеи об этом?

Ответы

Ответ 1

Если вы хотите использовать канал в другом модуле, добавьте модуль, где труба объявлена ​​в imports: [...] модуля, где вы хотите повторно использовать этот канал, вместо добавления его в declarations: [] несколько модулей.

Например:

@NgModule({
    imports: [BrowserModule],
    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 { }