再会。
请帮我解决以下问题: 我有一个应用程序配置文件 - app.config.json 它包含一些有用的信息。还有一个尊重此文件结构的界面。此外,还有一项服务可以将文件中的数据加载到静态接口对象中。但是,当应用程序启动时,似乎没有发生下载。
app.config.json
{
"appUrl": "http://localhost:8080/asterisk-prime",
"routes": {
"device": "device",
"extension": "extension",
"queue": "queue",
"queueMember": "queueMember"
},
"apiEndpoints": {
"device": "/api/device",
"extension": "/api/extension",
"queue": "/api/queue",
"queueMember": "/api/queueMember"
},
"stompEndpoint": "/socket"
}
iapp.config.ts
export interface IAppConfig {
appUrl: string;
routes: {
device: string,
extension: string,
queue: string,
queueMember: string
};
apiEndpoints: {
device: string,
extension: string,
queue: string,
queueMember: string
};
stompEndpoint: string;
}
app.config.service.ts
@Injectable({
providedIn: 'root'
})
export class AppConfigService {
static settings: IAppConfig;
constructor(private httpClient: HttpClient) {
}
loadConfig() {
const configFile = 'src/assets/config/app.config.json';
return new Promise<void>((resolve, reject) => {
this.httpClient.get<IAppConfig>(configFile)
.toPromise()
.then(response => {
AppConfigService.settings = response;
LoggerService.log('Config was loaded');
resolve();
})
.catch(err => {
LoggerService.error('Error while loading config.', err);
reject(`Could not load file '${configFile}': ${JSON.stringify(err)}`);
});
});
}
}
app.module.ts
...
export function loadConfig(appConfigService: AppConfigService) {
return () => appConfigService.loadConfig();
}
...
providers: [
AppConfigService,
{
provide: APP_INITIALIZER,
useFactory: loadConfig,
deps: [AppConfigService],
multi: true
}
],
...
实际上,错误发生在路由初始化期间的路由模块中。
应用程序路由.module.ts
const routes: Routes = [
{path: '', redirectTo: '/', pathMatch: 'full'},
{path: '', component: HomePageComponent},
{path: 'about', component: AboutPageComponent},
{path: AppConfigService.settings.routes.device, loadChildren: './path/to/children.module#ChildrenModule'},
{path: AppConfigService.settings.routes.extension, loadChildren: './path/to/children.module#ChildrenModule'},
{path: AppConfigService.settings.routes.queue, loadChildren: './path/to/children.module#ChildrenModule'},
{path: AppConfigService.settings.routes.queueMember, loadChildren: './path/to/children.module#ChildrenModule'}
浏览器错误:Cannot read property 'routes' of undefined
。
目前,我决定将除路由之外的所有内容移至单独的配置文件。留在应用程序内的路由。我使用声明的令牌通过路由实现配置。
iapp.config.routes.ts
app.config.routes.ts
app.module.ts
在组件中使用 AppConfigRoutes(示例):
header.component.ts
用法
app-routing.module.ts
基本上保持不变,只有对象发生了变化。