Actualmente estoy tratando de crear mi primera biblioteca Angular 2, una tubería de traducción. En este momento, estoy tratando de hacer que el desarrollador pueda insertar un objeto con traducciones en el módulo para que la tubería pueda usarlo.
¿Cómo puedo insertar algún tipo de configuración/objeto en mi biblioteca para que todos mis componentes, tuberías y servicios puedan usarlo?
Mi biblioteca se parece a:
índice.ts
import { NgModule, ModuleWithProviders } from '@angular/core'; import { CommonModule } from '@angular/common'; import { TranslatePipe } from './translate.pipe'; export * from './translate.pipe'; @NgModule({ imports: [ CommonModule ], declarations: [ TranslatePipe ], exports: [ TranslatePipe ] }) export class TranslateModule { static forRoot(): ModuleWithProviders { return { ngModule: TranslateModule, providers: [] }; } }traducir.pipe.ts
import { Injectable, PipeTransform, Pipe } from '@angular/core'; @Pipe({ name: 'translate' }) @Injectable() export class TranslatePipe implements PipeTransform { public translations: any = null; constructor () { this.translations = {}; } transform(key: string): string { let translation = key; if (key in this.translations) translation = this.translations[key]; return translation; } }Mi proyecto de prueba:
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { AppComponent } from './app.component'; import { TranslateModule } from 'translate-pipe'; @NgModule({ declarations: [ AppComponent, TranslateModule ], imports: [ BrowserModule, FormsModule, HttpModule ], providers: [ TranslateModule ], bootstrap: [AppComponent] }) export class AppModule { }Simplemente deje que el usuario pase un objeto de configuración al método forRoot() , luego configúrelo como un servicio
import { InjectionToken } from '@angular/core'; export const TRANSLATE_CONFIG = new InjectionToken(); export interface TranslateConfig { someProp?: string; anotherProp?: string; } export class TranslateModule { // config is optional. You can use configure default below static forRoot(config?: TranslateConfig) { // <======== const conf = createConfig(config); // maybe set some defaults return { ngModule: TranslateModule, providers: [ { provide: TRANSLATE_CONFIG, useValue: conf } ] } } }Luego, donde sea que necesite inyectar la configuración, simplemente hágalo (en su tubería)
import { Inject } from '@angular/core'; import { TranslateConfig, TRANSLATE_CONFIG } from './wherever'; constructor(@Inject(TRANSLATE_CONFIG) config: TranslateConfig) {}El usuario haría
imports: [ TranslateModule.forRoot({ someProp: someValue, anotherProp: anotherValue }) ]