【发布时间】:2018-06-20 15:28:41
【问题描述】:
Angular 5 - 预加载配置文件以供跨应用程序使用
我正在寻找有关如何预加载配置文件以允许跨应用程序使用的答案,这是答案 - 最初的实现来自:https://github.com/angular/angular/issues/9047
app.module.ts
import { AppConfigService } from './services/app-config.service';
export function init_app(configService: AppConfigService){
// Load Config service before loading other components / services
return () => {
return configService.load();
};
}
providers: [AppConfigService,
{
'provide': APP_INITIALIZER,
'useFactory': init_app,
'deps': [AppConfigService],
'multi': true,
}
]
app-config.service.ts
import { Injectable } from '@angular/core';
import {HttpClient, HttpResponse} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class AppConfigService {
config: any;
constructor(private http: HttpClient) { }
load(): Promise<any> {
return this.http.get('path/to/app-config.json')
.toPromise()
.then(res => this.config = res)
.catch(this.handleError);
}
private handleError(error: HttpResponse<any> | any) {
let errMsg: string;
if (error instanceof HttpResponse) {
const currentError: any = error;
const body = currentError.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
return new Promise((resolve) => {
resolve(errMsg);
});
}
}
使用(来自其他服务/组件):
import {AppConfigService} from './app-config.service';
constructor(private configService: AppConfigService) {
console.log("configService: ",this.configService.config)
}
【问题讨论】:
-
如果这是一个答案,您应该将其作为问题的答案发布。不作为一个问题。或将其发布为博客文章。
标签: angular