gpt4 book ai didi

Angular 5 - 预加载配置文件

转载 作者:太空狗 更新时间:2023-10-29 18:01:10 24 4
gpt4 key购买 nike

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)
}

最佳答案

我有一个类似于您的设置,但是,在我的情况下,调用延迟加载模块时数据不是持久的。我必须先将它加载到 session 存储中,然后才能使用它。当我从服务中检索数据时,“config”变量为空,我从内存中检索它并将其分配给变量,一旦我这样做,它就可供服务使用。

//
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 { }

我错过了什么?为什么我需要将配置存储在 session 存储中。目前此解决方法有效。

关于Angular 5 - 预加载配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47791578/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com