how can we use environment variable in angular version >=2

后端 未结 3 823
离开以前
离开以前 2021-01-02 06:44

I am now reading the angular4 doc, and noticed, there is one folder, environments, and under which, there are multiple environment files, such as environment.ts, environment

3条回答
  •  渐次进展
    2021-01-02 07:24

    If you are using CLI then in .angular-cli.json file, place this code. (From angular 6 onward, .angular-cli.json file is renamed to .angular.json)

    "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    

    In dev environment file, you can write

    export const environment = {
    production: false,
    url: 'http://something.com'
    };
    

    And in prod environment file, you can write

    export const environment = {
    production: true,
    url: 'http://something.com'
    }
    

    In components or services, you can use like

    import {environment} from '../../environments/environment';
    environment.url;
    

    You can command:

    ng serve --dev     // Or 
    ng serve --prod
    

    Note: you should have environments directory directly in app directory and both environment files should be there.

提交回复
热议问题