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,
}
]
应用-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)
}
答案 0 :(得分:0)
我有类似于你的设置,但是,在我的情况下,调用延迟加载模块时数据不是持久的。我必须首先将它加载到会话存储中,而不是我可以使用它。当我从服务中检索数据时,“config”变量为null,我从内存中检索它并将其分配给变量,一旦我这样做,它就可供服务使用。
//
import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse, HttpHeaders } from '@angular/common/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { DataService } from './data.service';
@Injectable()
export class ConfigService {
private config: any = null;
private env: any = null;
// -----------------------------------------------------------------------------------
constructor(private http: HttpClient, private dataService: DataService) { }
// -----------------------------------------------------------------------------------
public load(url?: string): Promise<any> {
const defaultUrl: string = (url === undefined ? 'appConfig.json' : url);
const headers = new HttpHeaders();
const options: any = {
url: defaultUrl,
headers: headers,
withCredentials: false,
responseType: 'json'
};
return this.http.get(defaultUrl, options)
.toPromise()
.then((data: any) => {
this.config = data;
this.dataService.Push('ConfigData', this.config);
})
.catch(this.handleError);
}
// -----------------------------------------------------------------------------------
// from https://stackoverflow.com/questions/47791578/angular-5-preload-config-file
// -----------------------------------------------------------------------------------
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);
});
}
// -----------------------------------------------------------------------------------
public getConfig(key: any): any {
if (null == this.config) {
// pull from storage
this.config = this.dataService.Get('ConfigData');
}
if (this.config && this.config.hasOwnProperty(key)) {
return this.config[key];
}
return null;
}
// -----------------------------------------------------------------------------------
}
在我的app.module.ts
中//
import { NgModule, ErrorHandler, LOCALE_ID, APP_INITIALIZER, Injector } from '@angular/core';
import { HttpClient, HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatToolbarModule } from '@angular/material';
import { Ng2Webstorage } from 'ngx-webstorage';
import {ConfigService, SharedModule } from '@mylib/mylib-angular-library';
// --------------------------------------------------------------------------
export function configServiceFactory(config: ConfigService) {
return () => {
return config.load();
}
}
// --------------------------------------------------------------------------
@NgModule({
imports: [
BrowserModule
, HttpClientModule
, BrowserAnimationsModule
, Ng2Webstorage
, SharedModule // <-- ConfigService provided in this module
...
],
declarations: [
...
],
providers: [
{ provide: APP_INITIALIZER, useFactory: configServiceFactory, deps: [ConfigService], multi: true }
],
bootstrap: [AppComponent]
})
export class MainModule { }
我错过了什么?为什么我需要将配置存储在会话存储中。目前这种解决方法有效。
答案 1 :(得分:-1)
在您的数据服务中:
import { Http } from '@angular/http';
export class dataService
{
constructor(private _http: Http){}
getConfig()
{
return this._http.get("appData.json")
.map(res => res.json());
}
}
在您的组件中:
fetchConfig()
{
this.subscription
= this.dataService
.getConfig()
.subscribe
(
config =>
{
if(config) this.configuration = config.data;
}
);
}
ngOninit(){ fetchConfig(); }
在您的appData.json中:
{
"data" :
{
"config1" : "x",
"config2" : "y"
}
}
我有一个github项目,它是在Angular 5中完成的一个示例着陆页,可将数据从src / assets / data / appData.json的json配置文件中加载
https://github.com/oneinazillion/landing-page
我希望这可能有用。