简体   繁体   English

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

[英]Trying to set environment variables in appSettings.json - Angular and Typescript

I am basically trying to set the API URL path in appSettings so I can change back and forth from prod and dev environments easily.我基本上是在尝试在 appSettings 中设置 API URL 路径,这样我就可以轻松地在 prod 和 dev 环境中来回切换。

This is my appSettings.json file.这是我的 appSettings.json 文件。 apiURL is the variable I am trying to set and get. apiURL 是我要设置和获取的变量。

{
 "Logging": {
"LogLevel": {
  "Default": "Information",
  "Microsoft": "Warning",
  "Microsoft.Hosting.Lifetime": "Information"
}
  },
 "AllowedHosts": "*",
 "apiURL": "http://10.241.2.68:8132/api"
}

Here is my page that is trying to access the environment variable that I set in appSettings.json.这是我的页面,它试图访问我在 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";
}

As stated in comment, appsettings.json is not for angular application.如评论中所述,appsettings.json 不适用于 angular 应用程序。 here you can go through this tutorial to find necessary steps for using enviornment.在这里您可以通过本教程找到使用环境的必要步骤。 here are some quick steps:以下是一些快速步骤:

import { environment } from './../environments/environment';
...
const baseUrl: string = environment.baseUrl;

where environment.ts may look like environment.ts 可能看起来像的地方

export const environment = {
  production: false,
  baseUrl: "http://localhost:45644/api/",
};

live example here活的例子在这里

I would suggest not using environment.ts since this is a build time configuration.我建议不要使用 environment.ts,因为这是构建时配置。

What you are actually looking for is some way to fetch your app-settings.json file depending on the environment, at run time.您实际上正在寻找的是在运行时根据环境获取您的 app-settings.json 文件的某种方法。 This means you can package your code and promote the packaged code through your environments, without rebuilding.这意味着您可以 package 您的代码并通过您的环境推广打包的代码,而无需重新构建。

Angular has something called APP_INITIALIZER which you can use to achieve this. Angular 有一个叫做APP_INITIALIZER的东西,你可以用它来实现这个。

  1. Set up your app-settings.json (app-settings.qa.json, app-settings.prod.json) in assets/config folder在 assets/config 文件夹中设置您的 app-settings.json (app-settings.qa.json, app-settings.prod.json)

  2. Configure an AppConfigService angular service.配置 AppConfigService angular 服务。

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

  1. Configure the AppService using the APP_INITIALIZER as the injection token in your AppModule使用 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 { }

Now you can use this service to fetch the baseURL using dependency injection现在您可以使用此服务通过依赖注入获取 baseURL

Below is an example service, what yours might look like.下面是一个示例服务,您的服务可能看起来像这样。 Note the constructor and the apiUrl private class variable注意构造函数和 apiUrl 私有 class 变量

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

from here, you will need to use your deployment method (azure devops pipelines, for example) to rename the appropriate file in the assets folder according to your env从这里开始,您将需要使用您的部署方法(例如,azure devops 管道)根据您的环境重命名 assets 文件夹中的相应文件

qa: rename app-settings.qa.json -> app-settings.json prod: rename app-settings.prod.json -> app-settings.json qa: rename app-settings.qa.json -> app-settings.json prod: rename app-settings.prod.json -> app-settings.json

And with that you will have a runtime app config有了它,您将拥有一个运行时应用程序配置

You should follow these steps:您应该按照以下步骤操作:

  1. Create a .env file in the root directory of your project and add environment-specific variables on new lines in the form of NAME=VALUE like this:在项目的根目录中创建一个.env文件,并以NAME=VALUE的形式在新行中添加特定于环境的变量,如下所示:
API_URL=http://localhost:45644/api/
  1. Use dotenv's tools that loads environment variables from a .env file into process.env object使用dotenv 的工具将环境变量从.env文件加载到process.env object

  2. Install custom-webpack as a dev dependency:安装custom-webpack作为开发依赖:

npm install -D @angular-builders/custom-webpack
  1. Modify your Angular configurations – angular.json – to use the new builder (custom-webpack)修改您的 Angular 配置 – angular.json – 使用新的构建器(custom-webpack)
"projects": {
    "name-of-the-project": {
      //...
      "architect": {
        "build": {
          "builder":"@angular-builders/custom-webpack:browser"_,
          "options": {
            "customWebpackConfig": {
                "path":"custom-webpack.config.js"
            },
            //...
        //...
    } }
  1. Then, you are going to create your custom-webpack.config.js file at the root of your Angular Workspace and add the following content to retrieve your environment variables and pass them to your builder:然后,您将在 Angular 工作区的根目录中创建您的custom-webpack.config.js文件,并添加以下内容以检索您的环境变量并将它们传递给您的构建器:
const webpack = require('webpack')
    require('dotenv').config()
    module.exports = {
      plugins: [
        new webpack.DefinePlugin({
          $ENV: {
            API_URL: JSON.stringify(process.env.API_URL),
          },
        }),
      ],
    }
  1. Finally to use your environment variables in Angular,you are going to add some typings, so that you can reference to your $ENV variable from webpack above within our Angular app.最后,要在 Angular 中使用您的环境变量,您将添加一些类型,以便您可以在我们的 Angular 应用程序中从上面的 webpack 引用您的$ENV变量。
  • First, let's create a typing.d.ts file inside your src directory at the root of your workspace and add the following content:首先,让我们在工作空间根目录的 src 目录中创建一个 typing.d.ts 文件,并添加以下内容:
declare var $ENV: Env;
    
    interface Env {
      API_URL: string;
    }
  • Then, inside the environment.ts, you need to read the environment variables passed to your application, so that your environment.ts would like this:然后,在 environment.ts 中,您需要读取传递给应用程序的环境变量,以便您的 environment.ts 如下所示:
export const environment = {
  production: true,
  environment: $ENV.API_URL,
};
  1. And for using your environment variables on your components:对于在组件上使用环境变量:
import { environment } from './../environments/environment';
...
public environment = environment.environment

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从 Angular 服务中的 .NET appSettings.json 文件读取环境变量? - Read an environment variable from a .NET appSettings.json file in an Angular service? 如何使用angular2从appsettings.json读取typescript文件的值? - How to read values from appsettings.json to typescript file using angular2? 如何使用angular4从appsettings.json到打字稿文件中读取键值 - How to read key values from appsettings.json to typescript file using angular4 如何在 Angular 10 中读取 appsettings.json 文件配置 - How to read appsettings.json file configuration in Angular 10 如何使用IIS appsettings.json在dotnet核心中配置Angular 6 URL重写 - How to configure Angular 6 URL rewrite in dotnet core using IIS appsettings.json 如何在 .NET Core 的 appSettings.json 上配置 IdentiyServer 设置? - How to configure IdentiyServer settings on appSettings.json of .NET Core? 从 .env 设置 Angular 6 环境变量 - Set up Angular 6 environment variables from .env 如何通过命令行在 cypress.json 文件中设置环境变量? (Angular CLI - nrwl nx) - How to set environment variables in cypress.json file through command line? (Angular CLI - nrwl nx) 在 APP_INITIALIZER 上应用初始化后加载 appsettings.json 文件 - appsettings.json file loading after app init on APP_INITIALIZER 如何添加/设置环境 Angular 6 angular.json 文件 - How to add/set environment Angular 6 angular.json file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM