在Angular 6中加载配置文件 [英] Loading configuration files in Angular 6

查看:104
本文介绍了在Angular 6中加载配置文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解如何在Angular 6中加载配置文件,我目前有一个ConfigureService,其中包含以下用于加载文件的代码:

I'm trying to understand how to load configuration files in Angular 6, I currently have a ConfigureService with the following code for loading the file:

configUrl = '../assets/config.json';
config: Config;

load() {
  console.log('loading configuration');
  this.getConfig().subscribe(
    (data: Config) => {
      console.log('Config request success');
      (this.config = data);
      console.log(this.config)
    }
  );
}

private getConfig() {
  return this.http.get<Config>(this.configUrl);
}

在ConfigureService的构造函数中调用负载的地方

Where load is called in the constructor of ConfigureService

我使用此服务获取我的api消费者服务的Url字符串,并且确实运行成功(console.logs显示在dev窗口中),只是这些服务没有及时在其服务中使用其各自的url字符串OnInit方法和其他服务尝试从未定义的配置对象中提取字符串时会引发错误.

I use this service to get my Url strings for my api consumer services, and it does run successfully (the console.logs show in the dev window), just not in time for those services to use their respctive url strings in their OnInit methods, and the other services throw errors as they are trying to pull the strings from an undefined config object.

我试图通过在app.module中指定它们并在启动之前加载它们来读取它们,如下所示:

I have tried to read them in by specifying them in the app.module and loading them before startup as seen here:

https://gist.github.com/fernandohu/122e88c3bcd210bbe41c608c36306db9

但是,当我尝试该方法时,它告诉我在服务器上找不到文件,即使指定的路径正确,控制台中的错误也会返回404.

Yet when I try that method, it tells me that the files could not be found on the server, and the error in the console returns 404, even though the path specified is correct.

如何确保config服务首先运行,以便依赖它的其他服务在初始化完成之前不尝试检索数据?

How can I ensure that the config service runs first so that other services who are dependent on it do not try to retrieve data before it has finished its initialization?

推荐答案

这是一个很好的问题,我们也有不同的服务器(开发,质量控制,阶段,产品),因此,为每个环境创建单独的版本非常耗时,我从未尝试过为每种环境创建单独的环境文件的方法,我们通过将Api Urls和常量存储在json文件中解决了这个问题.

It is a very good question,We too have different servers ( Dev, QC ,Stage ,Prod), so creating a separate build for every environment is very time consuming process , I have never tried this approach of creating separate environment file for every environment, We solved this problem by storing the Api Urls and constants in a json file.

因此首先创建一个json文件并将其放置在 assets 文件夹中.

so first of all create a json file and place it inside assets folder.

Config.json

{
    "url":{
    "apiUrl": "http://localhost:58357/"
    }
}

创建一个模型类,该模型类应具有与 Config.json 文件

Create a model class which should have the properties with same name as is Config.json file

Config.ts

 export class Config {
    url: {
        apiUrl: string;
    };
}

创建服务以导入 Config.json 文件

app.config.service.ts

import { Injectable } from '@angular/core';
import { Config } from './models/config';
import { HttpClient, HttpBackend, HttpResponse } from '@angular/common/http';
import { Observable } from '../node_modules/rxjs';
import { map } from 'rxjs/operators';

@Injectable({
providedIn: 'root'
})
export class AppConfig {

static Settings: Config;
private http: HttpClient;
constructor(private httpBackEnd: HttpBackend) {
    this.http = new HttpClient(httpBackEnd);
}
load() {
    const jsonFile = 'assets/config.json';
    return new Promise<void>((resolve, reject) => {
    this.http.get(jsonFile).toPromise().then((response: Config) => {
       AppConfig.Settings = <Config>response;
       resolve();
    }).catch((response: any) => {
       reject(`Could not load file '${jsonFile}': ${JSON.stringify(response)}`);
    });
    });
 }
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { AppComponent } from './app.component';
import { AppConfig } from '../app.config.service';
import { HttpClientModule } from '../../node_modules/@angular/common/http';


export function initConfig(appConfig: AppConfig) {
return () => appConfig.load();
}

@NgModule({
declarations: [
AppComponent
],
  imports: [
  BrowserModule,
  HttpClientModule,
  ],
providers: [
 AppConfig, { provide: APP_INITIALIZER, useFactory: initConfig, deps: [AppConfig], multi: true },
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

在要使用json文件中存储的密钥的任何组件文件中导入AppConfig.

import AppConfig in any component file where you want to use the keys stored in the json file.

app.component.ts

import { Component } from '@angular/core';
import { AppConfig } from '../app.config.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
 })
 export class AppComponent {
 title = 'ConstantsManagerDemo';
 constructor() {
 const apiUrl = AppConfig.Settings.url.apiUrl;
 alert(apiUrl);
  }
 }

转到 tsconfig.json 文件并添加

"allowSyntheticDefaultImports" :true,  
under compilerOptions

这篇关于在Angular 6中加载配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆