sr9*_*yar 5 javascript angular angular6
有一个使用环境变量的 angular 6 项目 ./project/src/environments/environment.prod.ts
export const environment = {
production: true,
testVar: 'gg',
};
Run Code Online (Sandbox Code Playgroud)
这个项目的后端在一个.env文件中也有 env 变量,所以很多变量重复了 angular env 变量。有类似的东西会很好
export const environment = {
production: true,
testVar: process.env.TEST_VAR
};
Run Code Online (Sandbox Code Playgroud)
,所以我不必复制变量。
IE
我想从.env文件中解析变量,并在服务器上的打字稿编译期间将它们的值分配给角度环境变量。
如何才能做到这一点?也许用webpack?
更新
一些澄清。我的 .env 文件不包含 json。它看起来像这样:
TEST_VAR=1
Run Code Online (Sandbox Code Playgroud)
更新
由于ng eject 不适用于 Angular 6,我似乎无法侵入 webpack 配置。这里好像死路一条。
弹出
概述
暂时禁用。
弹出您的应用程序并输出正确的 webpack 配置和脚本。
您可以创建一个配置文件并在运行时填充。
1)使用您的变量在资产文件夹中创建一个文件(app-config.json)
{ "servicesUrl": "https://localhost:8080/api"}
Run Code Online (Sandbox Code Playgroud)
2)创建一个服务(AppConfigService)来读取文件。
@Injectable()
export class AppConfigService {
private appConfig;
constructor (private injector: Injector) { }
loadAppConfig() {
let http = this.injector.get(HttpClient);
return http.get('/assets/app-config.json')
.toPromise()
.then(data => {
this.appConfig = data;
})
}
get config() {
return this.appConfig;
}
Run Code Online (Sandbox Code Playgroud)
3) 接下来我们需要告诉应用程序执行服务的 loadAppConfig() 方法。
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { AppConfigService } from './services/app-config.service';
@NgModule({
...,
providers: [
AppConfigService,
{
provide: APP_INITIALIZER,
useFactory: appInitializerFn,
multi: true,
deps: [AppConfigService]
}
],
...
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)
4)创建一个名为“appInitializerFn”的函数来调用AppModule(app.module.ts)中的我们的服务
const appInitializerFn = (appConfig: AppConfigService) => {
return () => {
return appConfig.loadAppConfig();
}
};
...
@NgModule({
...
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)
5)导入环境并使用它:示例
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { AppConfigService } from './services/app-config.service';
@Injectable()
export class DataContextService {
basePath: string;
constructor (private environment: AppConfigService, private http: HttpClient) {
this.basePath = environment.config.servicesBasePath;
}
getNames() {
return this.http.get(this.basePath + '/names/');
}
}
Run Code Online (Sandbox Code Playgroud)
欲了解更多信息,请参阅: 链接
| 归档时间: |
|
| 查看次数: |
9723 次 |
| 最近记录: |