【问题标题】:Angular 5 - preload config fileAngular 5 - 预加载配置文件
【发布时间】: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


【解决方案1】:

我有一个类似于你的设置,但是,在我的情况下,调用延迟加载模块时数据不是持久的。我必须先将它加载到会话存储中才能使用它。当我从服务中检索数据时,“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 Storage 中。目前,此解决方法有效。

【讨论】:

  • 我会等待配置请求完成,然后相应地设置我的服务(同样,不是理想的方式......):(MyService 应该实现 setConfig 方法 - 根据收到的配置设置配置数据) 导出函数 configServiceFactory(config: ConfigService, myService:MyService) { return () => { const config = configService.load(); config.then((data) => { myService.setConfig(data); }) 返回配置; }; }
  • export function configServiceFactory(config: ConfigService, myService:MyService) { return () =&gt; { const config = configService.load(); config.then((data) =&gt; { myService.setConfig(data); }) return config; }; }
  • 感谢 Yonatan Ayalon 的帮助。问题是我在加载惰性模块时再次注入服务,该模块创建了一个新实例。一旦我删除它并且只在父模块中注入服务,它就会按预期工作。
猜你喜欢
  • 1970-01-01
  • 2017-06-25
  • 2016-10-25
  • 1970-01-01
  • 2018-11-16
  • 1970-01-01
  • 1970-01-01
  • 2021-07-27
  • 2018-08-12
相关资源
最近更新 更多