[英]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/",
};
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的东西,你可以用它来实现这个。
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)
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;
}
}
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:您应该按照以下步骤操作:
.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/
Use dotenv's tools that loads environment variables from a .env
file into process.env
object使用dotenv 的工具将环境变量从
.env
文件加载到process.env
object
Install custom-webpack
as a dev dependency:安装
custom-webpack
作为开发依赖:
npm install -D @angular-builders/custom-webpack
"projects": {
"name-of-the-project": {
//...
"architect": {
"build": {
"builder":"@angular-builders/custom-webpack:browser"_,
"options": {
"customWebpackConfig": {
"path":"custom-webpack.config.js"
},
//...
//...
} }
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: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),
},
}),
],
}
$ENV
variable from webpack above within our Angular app.$ENV
变量。declare var $ENV: Env;
interface Env {
API_URL: string;
}
export const environment = {
production: true,
environment: $ENV.API_URL,
};
import { environment } from './../environments/environment';
...
public environment = environment.environment
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.