我的应用具有以下结构:
src
|-- modules
| |-- app2-module
|
|-- shared-common
| |-- services
| |-- rest.services.ts
|
|-- app.module.ts
rest.services必须是可配置的。
如果在app2(app2-module
)中调用了get方法,例如,
rest/app2-api/getCompanyList
;如果它在app1(app.module.ts
中调用,则get方法使用,例如rest/app1-api/getCompanyList
。
所以我以这种方式创建了一个可配置的共享模块
export default interface SharedCommonConfig {
createApiUrl(api: string): string;
}
export const SharedCommonConfigService): = new InjectionToken<SharedCommonConfig>('SharedCommonConfig');
export class SharedCommonModule {
static forRoot(config: SharedCommonConfig): ModuleWithProviders {
return {
ngModule: SharedCommonModule
providers: [
{
provide: SharedCommonConfigService): Service,
useValue: config
},
RestService
],
};
}
}
然后我在app.module.ts
@NgModule({
imports: [
BrowserModule,
App2Module,
SharedCommonModule .forRoot({
createApiUrl: (api: string) => {
return `/rest/app1-app/${api}`;
}
})
],
})
export class AppModule implements OnInit {}
和在App2Module中
@NgModule({
imports: [
BrowserModule,
SharedCommonModule .forRoot({
createApiUrl: (api: string) => {
return `/rest/app2-app/${api}`;
}
})
],
})
export class App2Module implements OnInit {}
当用户导航到URL http://example.com/#/app2/时,屏幕上显示 App2Module,在这种情况下,其余服务必须以/rest/app2-app
作为前缀来调用api;但这是行不通的,因为只能读取app.module.ts中的配置。
有可能不将rest.service用作单例吗?
答案 0 :(得分:0)
以这种方式在根app.module中导入共享服务的操作将使它成为单例。
为避免这种情况,您需要将app1.module和app2.module分开,然后在这两个服务中注册服务,然后不在主app.module中注册服务。
因此,您需要:
@NgModule({
imports: [
BrowserModule,
App1Module,
App2Module
],
})
export class AppModule implements OnInit {}
...,然后分别进行App1Module和App2Module的注册,就像您对App2Module所做的那样:
应用1:
@NgModule({
imports: [
BrowserModule,
SharedCommonModule .forRoot({
createApiUrl: (api: string) => {
return `/rest/app1-app/${api}`;
}
})
],
})
export class App1Module implements OnInit {}
应用2:
@NgModule({
imports: [
BrowserModule,
SharedCommonModule .forRoot({
createApiUrl: (api: string) => {
return `/rest/app2-app/${api}`;
}
})
],
})
export class App2Module implements OnInit {}