尝试在 appSettings.json 中设置环境变量 - Angular 和 Typescript

Tdi*_*ges 3 typescript angularjs-directive angular

我基本上尝试在 appSettings 中设置 API URL 路径,以便我可以轻松地在生产和开发环境中来回更改。

这是我的 appSettings.json 文件。apiURL 是我试图设置和获取的变量。

{
 "Logging": {
"LogLevel": {
  "Default": "Information",
  "Microsoft": "Warning",
  "Microsoft.Hosting.Lifetime": "Information"
}
  },
 "AllowedHosts": "*",
 "apiURL": "http://10.241.2.68:8132/api"
}
Run Code Online (Sandbox Code Playgroud)

这是我的页面,它尝试访问我在 appSettings.json 中设置的环境变量。

import { Injectable } from '@angular/core';
// import { Defendant } from 'src/app/Models/Defendant';
import { Charge } from 'src/app/Models/Charge';
import { DefendantItem } from '../Models/DefendantItem';
import { Defendant_Charge } from '../Models/Defendant_Charge';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AppConfiguration } from "read-appsettings-json";  
@Injectable({
providedIn: 'root'
})
export class ChargeService {
//console.log(AppConfiguration.Setting().apiURL);
////////////////////////////////////////////////////////////////////
//  below is where I am trying to reference the environment variable
//  the entire program bombs and displays "GET \" on the page.
ChargeControllerUrl = AppConfiguration.Setting().apiURL + "/Charges";
//ChargeControllerUrl = "http://10.241.2.68:8132/api/Charges";
}
Run Code Online (Sandbox Code Playgroud)

Gan*_*zal 6

我建议不要使用environment.ts,因为这是构建时配置。

您实际上正在寻找的是在运行时根据环境获取 app-settings.json 文件的某种方法。这意味着您可以打包代码并在您的环境中推广打包的代码,而无需重新构建。

Angular 有一个叫做APP_INITIALIZER的东西,你可以用它来实现这一点。

  1. 在 asset/config 文件夹中设置 app-settings.json (app-settings.qa.json、app-settings.prod.json)

  2. 配置 AppConfigService 角度服务。

//app/services/app-config.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

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

  private appConfig: any;
  private http : HttpClient;

  constructor(http: HttpClient) {
    this.http = http;
  }

  loadAppConfig() {
    return this.http.get('/assets/config/app-settings.json')
      .toPromise()
      .then(config => {
        this.appConfig = config;
      });
  }

  get apiBaseUrl() : string {
    return this.appConfig.apiBaseUrl;
  }
}

Run Code Online (Sandbox Code Playgroud)
  1. 使用 APP_INITIALIZER 作为 AppModule 中的注入令牌来配置 AppService
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER } from '@angular/core';

import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
import { AppConfigService } from './services/app-config/app-config.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [
    {
      provide : APP_INITIALIZER,
      multi : true,
       deps : [AppConfigService],
       useFactory : (appConfigService : AppConfigService) =>  () => appConfigService.loadAppConfig()
    }

  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Run Code Online (Sandbox Code Playgroud)

现在您可以使用此服务通过依赖注入来获取基本URL

下面是一个示例服务,您的服务可能是什么样子的。注意构造函数和 apiUrl 私有类变量

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { IempList } from '../interfaces/iemp-get-res';
import { map } from 'rxjs/operators';
import { AppConfigService } from 'src/app/services/app-config/app-config.service';

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

  constructor(private httpClient: HttpClient, private appConfigService: AppConfigService) { }

  private apiUrl = this.appConfigService.apiBaseUrl + '/api/employee';

  public getEmp(): Observable<IempList> {
    return this.httpClient.get(this.apiUrl)
      .pipe(map((res: IempList) => res));
  }

  public deletEmp(id): Observable<any> {
    return this.httpClient.delete(this.apiUrl + '/' + id)
      .pipe(map((res: any) => res));
  }

  public createEmp(formData): Observable<any> {
    return this.httpClient.post(this.apiUrl + '/create', formData.data)
      .pipe(map((res: any) => res));
  }

  public editEmp(formData): Observable<any> {
    return this.httpClient.post(this.apiUrl + '/update', formData.empData)
      .pipe(map((res: any) => res));
  }
}
Run Code Online (Sandbox Code Playgroud)

从这里开始,您将需要使用部署方法(例如,azure devops pipelines)根据您的环境重命名资产文件夹中的相应文件

qa:重命名 app-settings.qa.json -> app-settings.json prod:重命名 app-settings.prod.json -> app-settings.json

这样你就会有一个运行时应用程序配置