Sgiobair
Sgiobair

Reputation: 305

Accessing .ENV Properties with Angular2 Typescript and ServerJS

I've been going through the Angular2 Quickstart and tutorials and now I'm trying to get set up pulling data from a live REST Api. I need to pass in authentication parameters with the Api call and everything I'm reading says I should be putting those parameters into the ENV variables.

I can't work out exactly how I should be doing this. I've created a .env file on my local server, I've used NPM to instal dotenv to my project, but none of the examples I can find for how to use dotenv seem to fit with the TypeScript import syntax I'm used to.

Here's my main.ts:

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

bootstrap(AppComponent);

And a sample 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 { 

}

Any help would be appreciated. I've been out of the coding loop for a while and this is all a bit new to me.

Bonus question, would I still have the .env file when I go to a live server or does it change?

Upvotes: 2

Views: 3100

Answers (2)

frankfullstack
frankfullstack

Reputation: 550

I think you need to initialize the dotenv config method:

dotenv.config();

I usually use as follow:

import * as dotenv from 'dotenv';

//Later in your code
dotenv.config();

Then you may use your environment variables.

Upvotes: 3

Mrinal Deo
Mrinal Deo

Reputation: 171

I was having the same problem. Couldn't find a proper solution so I did something like this:

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

Upvotes: 0

Related Questions