gpt4 book ai didi

javascript - Angular 2库配置

转载 作者:太空狗 更新时间:2023-10-29 18:31:18 25 4
gpt4 key购买 nike

目前我正在尝试创建我的第一个 Angular 2 库,一个翻译管道。现在我正试图让开发人员能够将带有翻译的对象插入到模块中,以便管道可以使用它。

如何将某种配置/对象插入到我的库中,以便我的所有组件、管道和服务都可以使用它?

我的图书馆看起来像:

索引.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: []
};
}
}

翻译.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() 方法,然后将其设置为服务

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

然后在任何需要注入(inject)配置的地方,只需(在您的管道中)

import { Inject } from '@angular/core';
import { TranslateConfig, TRANSLATE_CONFIG } from './wherever';


constructor(@Inject(TRANSLATE_CONFIG) config: TranslateConfig) {}

用户会做

imports: [
TranslateModule.forRoot({
someProp: someValue,
anotherProp: anotherValue
})
]

关于javascript - Angular 2库配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43682296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com