Angular 2+,如何读取模块中的环境变量(webpack)



我不知道如何读取环境变量。我正在APP.module.browser.ts,中初始化APP_INITIALIZER

@NgModule({
bootstrap: [AppComponent],
imports: [
BrowserModule,
AppModuleShared,
AppAuthModule
],
declarations: [],
providers: [
{ provide: 'BASE_URL', useFactory: getBaseUrl },
{
provide: APP_INITIALIZER, // <-- HERE
useFactory: configurationServiceFactory,
deps: [ConfigurationService],
multi: true
},
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor, //AuthInterceptor,
multi: true
}
ConfigurationService,
ErrorLogService
]

在这个初始化之后,我得到了一些常量变量。我想读取我的环境变量。因此,我可以将其放入条件中,并可以根据我的条件导入我的模块,如下所示。

import { AccountsComponent } from "./customerList/components/accounts/accounts.component";
import { AccountsPlusComponent } from "./customerList/components/accounts-plus/accounts-plus.component";
let accountsInjection: any = ENV_VARIABLE ? AccountsComponent : AccountsPlusComponent;
@NgModule({
declarations: [
accountsInjection
],
imports: [
...

注意:我的项目中没有应用程序/环境/文件夹。。。(我还在想办法说(

编辑:我还想提供额外的信息,我正在使用WEBPACK,我应该使用另一种方法来获取我的环境变量吗?

如果您想访问变量env.variable_name

Dotenv是一个加载环境变量的零依赖模块。

安装:

npm install dotenv

在项目的根目录中创建一个.env文件。以NAME=VALUE的形式在新行中添加特定于环境的变量。例如:

apiUrl= 'url'
enviorement= 'dev'

组件内

require('dotenv').config()

使用变量作为:

process.env.appUrl,

这是针对角度6。但我们也可以在角度>2时有类似的配置。Angular.json

"configurations": {
"dev": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.dev.ts"
}
]
},
"test": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.qa.ts"
}
]
}

其他环境也是如此。

Package.json-

"start": "ng serve --configuration=dev",
"prod": "ng serve --configuration=prod",
"test": "ng serve --configuration=test",

组件内-

import { environment } from '/../environments/environment'; // as per your path
//use like
environment.property_name

最新更新