简体   繁体   中英

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.

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

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/'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM