使用Angular2 Typescript和ServerJS访问.ENV属性

我一直在通过Angular2快速入门和教程,现在我试图设置从一个活的REST Api拉数据。 我需要通过Api调用authentication参数,我正在阅读的一切,我应该把这些参数到ENVvariables。

我无法弄清楚我应该怎么做。 我已经在我的本地服务器上创build了一个.env文件,我已经使用NPM将dotenv安装到我的项目中,但是我找不到关于如何使用dotenv的示例,似乎与我使用的TypeScript导入语法至。

这是我的main.ts:

import { } from 'dotenv/config'; import { bootstrap } from '@angular/platform-browser-dynamic'; import { AppComponent } from './app.component'; bootstrap(AppComponent); 

和一个示例app.component.ts:

 import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: ` <h1>Up and running!</h1> <p>Do not show this at home: {{process.env.TWITTER_CONSUMER_KEY}}</p> `, styleUrls: ['style.css'] }) export class AppComponent { } 

任何帮助,将不胜感激。 我已经离开了编码循环了一段时间,这对我来说有点新鲜。

奖金的问题,当我去一个活的服务器,或者它改变时,我仍然会有.env文件吗?

我想你需要初始化dotenvconfiguration方法:

 dotenv.config(); 

我通常使用如下:

 import * as dotenv from 'dotenv'; //Later in your code dotenv.config(); 

那么你可以使用你的环境variables。

我遇到了同样的问题。 找不到合适的解决scheme,所以我做了这样的事情:

 import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: ` <h1>Up and running!</h1> <p>Do not show this at home: {{twitterConsumerKey}}</p> `, styleUrls: ['style.css'] }) export class AppComponent { public twitterConsumerKey:string; ngOnInit() { this.twitterConsumerKey = process.env.TWITTER_CONSUMER_KEY; } }