tschaka1904
tschaka1904

Reputation: 1499

Concatenate env variables in environment.ts

I'd like to reduce some redundancy in my environment.ts, as many of my env variables start with the same. So what I wanted to do is this:

export const environment = {
    base_url: '//www.myWebsite.co.uk/',
    ws_base_url: this.base_url + 'ws',
    download_base_url: this.base_url + 'download'
}

Rather then:

export const environment = {
    base_url: '//www.myWebsite.co.uk/',
    ws_base_url: '//www.myWebsite.co.uk/ws',
    download_base_url: '//www.myWebsite.co.uk/download'
}

But when I use the environment.ws_base_url I don't get //www.myWebsite.co.uk/ws, but undefined/ws. I was just wondering if this is really not working or if I'm just missing something.

Upvotes: 5

Views: 4556

Answers (3)

chrisbajorin
chrisbajorin

Reputation: 6153

You can just declare a variable outside the object:

const BASE_URL = '//www.myWebsite.co.uk/';

export const environment = {
    base_url: BASE_URL,
    ws_base_url: BASE_URL + 'ws',
    download_base_url: BASE_URL + 'download'
}

Upvotes: 4

Jeff
Jeff

Reputation: 96

Since people are showing more than one way to do this I thought I might as well add another way.

environment = {}
environment.base_url= '//www.myWebsite.co.uk/'
environment.ws_base_url= environment.base_url + 'ws'
environment.download_base_url= environment.base_url + 'download'

Just something that I saw with your first code, it looks like you were missing a ',' in your environment declaration. Right after the declaration of the base_url:

base_url: '//www.myWebsite.co.uk/'

Upvotes: 2

Tiep Phan
Tiep Phan

Reputation: 12596

also, using ES5 getter should work

const environment = {
    base_url: '//www.myWebsite.co.uk/',
    get ws_base_url() {
      return this.base_url + 'ws';
    },
    get download_base_url() { 
      return this.base_url + 'download'
    }
}

console.log(environment)

demo: https://jsbin.com/gujecaleru/edit?js,console

Upvotes: 2

Related Questions