أنغولار - تمرير بيانات التكوين باستخدام forRoot
أنا أحاول تمرير بيانات الإعدادات إلى مكتبة مخصصة في Angular.
في تطبيق المستخدمين، سيمررون بعض بيانات الإعداد لمكتبتي باستخدام forRoot
// Import custom library
import { SampleModule, SampleService } from 'custom-library';
...
// User provides their config
const CustomConfig = {
url: 'some_value',
key: 'some_value',
secret: 'some_value',
API: 'some_value'
version: 'some_value'
};
@NgModule({
declarations: [...],
imports: [
// User config passed in here
SampleModule.forRoot(CustomConfig),
...
],
providers: [
SampleService
]
})
export class AppModule {}
في مكتبتي المخصصة، وبالتحديد في index.ts، يمكنني الوصول إلى بيانات التكوين:
import { NgModule, ModuleWithProviders } from '@angular/core';
import { SampleService } from './src/sample.service';
...
@NgModule({
imports: [
CommonModule
],
declarations: [...],
exports: [...]
})
export class SampleModule {
static forRoot(config: CustomConfig): ModuleWithProviders {
// User config get logged here
console.log(config);
return {
ngModule: SampleModule,
providers: [SampleService]
};
}
}
سؤالي هو كيف أجعل بيانات الإعداد متاحة في SampleService للمكتبة المخصصة
حاليًا يحتوي SampleService على ما يلي:
@Injectable()
export class SampleService {
foo: any;
constructor() {
this.foo = ThirdParyAPI(/* I need the config object here */);
}
Fetch(itemType:string): Promise<any> {
return this.foo.get(itemType);
}
}
لقد قرأت المستندات الخاصة بمزودي الخدمات، ومع ذلك فإن مثال forRoot بسيط جدًا ولا يبدو أنه يغطي حالتي الخاصة.
الإجابة رقم 1
أنت قريب جدًا، فقط قدم كل من SampleService وconfig في وحدتك كما هو موضح أدناه:
export class SampleModule {
static forRoot(config: CustomConfig): ModuleWithProviders<SampleModule> {
// User config get logged here
console.log(config);
return {
ngModule: SampleModule,
providers: [SampleService, {provide: 'config', useValue: config}]
};
}
}
@Injectable()
export class SampleService {
foo: string;
constructor(@Inject('config') private config:CustomConfig) {
this.foo = ThirdParyAPI( config );
}
}
تحديث:
نظرًا لأن ModuleWithProviders في Angular 7 عام، فإنه يحتاج إلى ModuleWithProviders<SampleService>
