Angular CLI: Change REST API URL on build

后端 未结 7 1659
心在旅途
心在旅途 2021-02-02 08:58

I want to remove my local server prefix from my REST API URLs (example, http://localhost:8080) when building for production (ng build --prod).

I get that i

相关标签:
7条回答
  • 2021-02-02 09:47

    Dont hard code the URL. Use environment.prod.ts and environment.ts files which are inside src/environments. for localhost, in environment.ts file use some variable to save your url.

    export const environment = 
    {
        production: false,
        API_URL: 'http://localhost:8080',
    };
    

    for production, in environment.prod.ts

    export const environment = 
    {
        production: true,
        API_URL: 'http://api.productionurl.com',
    };
    

    When using in your code import the variable,

    import { environment } from '../../environments/environment';
    ....
    ....
    
    private API_URL= environment.API_URL;
    

    whenever your are using for production use angular cli command option

    ng build --env=prod
    

    The file contents for the current environment will overwrite these during build. The build system defaults to the dev environment which uses environment.ts, but if you do ng build --env=prod then environment.prod.ts will be used instead. The list of which env maps to which file can be found in .angular-cli.json.

    For more queries refer, https://angular.io/guide/deployment

    0 讨论(0)
提交回复
热议问题