How to declare pipe globally to use in different M

2019-01-22 18:03发布

问题:

Now i have a custom pipe created named CurrConvertPipe

import {Pipe, PipeTransform} from '@angular/core';
import {LocalStorageService} from './local-storage';
@Pipe({name: 'currConvert', pure: false})
export class CurrConvertPipe implements PipeTransform {
  constructor(private currencyStorage: LocalStorageService) {}

  transform(value: number): number {
     let inputRate = this.currencyStorage.getCurrencyRate('EUR');
    let outputputRate = this.currencyStorage.getCurrencyRate(localStorage.getItem('currency'));
    return value / inputRate * outputputRate;
  }
}

I need to use this in two different modules,

(i)  Module1
(ii) Module2

When i import in Module1 and Module2 it says an error saying it should be declared in a higher level module.

So i have declared inside the app.module.ts

import './rxjs-extensions';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CurrConvertPipe } from './services/currency/currency-pipe';
@NgModule({
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        AppRoutingModule,
        Module1,         
        Module2

    ],

    declarations: [
        AppComponent,
        CurrConvertPipe
    ],
    providers: [

    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

But when i use it in Module1, it throws an error The pipe 'currConvert' could not be found

回答1:

In Angular a good technique for sharing common directives, components, pipes, etc. is to use a so called shared module.

Those modules declare and export common parts, to make them usable for any of your other modules.

The fundamentals section of the angular documentation is a very good read about shared modules.

Let's take as example your currConvert-pipe.


  • Declare new NgModule called ApplicationPipesModule
  • Add the pipe to the declarations and exports arrays of the NgModule-decorator metadata
  • Add any modules that may be required for your pipe to work to the imports array

// other imports
import { CurrConvertPipe } from './{your-path}';

@NgModule({
  imports: [
    // dep modules
  ],
  declarations: [ 
    CurrConvertPipe
  ],
  exports: [
    CurrConvertPipe
  ]
})
export class ApplicationPipesModule {}

application-pipes.module.ts


  • import the created ApplicationPipesModule module into the modules where your pipe is going to be used, by adding it to the imports array

// other imports
import { ApplicationPipesModule } from './{your-path}';   

@NgModule({
 imports: [
   // other dep modules
   ApplicationPipesModule
 ],
 declarations: [],
 exports: []
})
export class MyModule1 {}

my-module1.module.ts


// other imports
import { ApplicationPipesModule } from './{your-path}';

@NgModule({
 imports: [
   // other dep modules
   ApplicationPipesModule
 ],
 declarations: [],
 exports: []
})
export class MyModule2 {}

my-module2.module.ts

EDIT: Improved answer text and example.



回答2:

You should make a module, i.e. SharedModule and declare your pipe there. Then you should export pipe in SharedModule and import your SharedModule in both Module1 and Module2. There's a great article in Angular's docs: https://angular.io/docs/ts/latest/guide/ngmodule.html#!#shared-module



回答3:

you can use Sharing Modules for share your service, directive, pipes, components

you have to create an module and import the pipes ,directive, services or components and set the declaration, export and providers for the services.

import the sharing module in to where ever you want and use it.

basically pipes and directives declared and exported in NgModules meta data. for services define forRoot which returns the providers to access other modules.

  • shareModule.ts

    
    import { NgModule, ModuleWithProviders } from '@angular/core';
    import { appDirective } from './{your-path}';
    import { appPipe } from './{your-path}';
    import { appService } from './{your-path}';
    
    @NgModule({
      declarations: [
        appPipe,
        appDirective
      ],
      exports: [
        appPipe,
        appDirective
      ]
    })
    export class SharingModule {
      static forRoot(): ModuleWithProviders {
        return {
          ngModule: SharingModule,
          providers: [ appService ]
        };
      }
    }
    
  • my-module1.module.ts

    
    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    
    import { myComponent } from './{your-path}';
    
    import { SharingModule } from './{your-path}';
    
    @NgModule({
      declarations: [
        myComponent
      ],
      imports: [
        BrowserModule,
        SharingModule.forRoot()  
      ],
    })
    export class AppModule {}
    

Like wise you can do in othe moduls also.