Angular 2库配置 [英] Angular 2 Library config
问题描述
当前,我正在尝试创建我的第一个Angular 2库,一个翻译管道.现在,我正在尝试使开发人员能够将带有翻译的对象插入模块,以便管道可以使用它.
Currently I am trying to create my first Angular 2 library, a translate pipe. Right now I am trying to make the developer able to insert an object with translations into the module so the pipe can use it.
如何将某种配置/对象插入到我的库中,以便我所有的组件,管道和服务都可以使用它?
How can I insert some sort of config/object into my library so all my components, pipes and services can use it?
我的图书馆看起来像:
index.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: []
};
}
}
translate.pipe.ts
translate.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;
}
}
我的测试项目:
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 { }
推荐答案
只需让用户将配置对象传递给 forRoot()
方法,然后将其设置为服务
Just let the user pass a config object to the forRoot()
method, then set it as a service
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 }
]
}
}
}
然后,无论您需要在哪里注入配置,只需(在管道中)
Then wherever you need to inject the config, just do (in your pipe)
import { Inject } from '@angular/core';
import { TranslateConfig, TRANSLATE_CONFIG } from './wherever';
constructor(@Inject(TRANSLATE_CONFIG) config: TranslateConfig) {}
用户会这样做
imports: [
TranslateModule.forRoot({
someProp: someValue,
anotherProp: anotherValue
})
]
这篇关于Angular 2库配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!