Snake Eyes
Snake Eyes

Reputation: 16764

Change url from service when build angular 6 project

In development, I use http://localhost:565565/api/v2 in an angular service to retrieve data from local server.

Now in production, I want to change that url to https://www.data.com/api/v2.

How to change with angluar cli ? I don't want manually change the big main.xxxxxxx.js file.

Until now I use ng build --prod but it is not enough.

Upvotes: 1

Views: 2796

Answers (2)

kboul
kboul

Reputation: 14600

Use the environments provided in angular.cli:

On environment.ts for development use

export const environment = {
    production: false,
    apiUrl: 'http://localhost:565565/api/v2'
};

On environment.prod.ts for production use:

export const environment = {
      production: true,
      apiUrl: 'https://www.data.com/api/v2'
};

Then depending on which environment you run your app the corresponding file will be used. If you run ng serve environment.ts will be used, if you run ng build --prod environment.prod.ts will be used.

Additionally you will need to import environment to your ts to use apiUrl

example in ts

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

and use it as environment.apiUrl

Upvotes: 3

Akj
Akj

Reputation: 7231

Use environment file:

ng build --environment=production

export const environment = {  
  production: true,
  apiUrl: "prod_Url"
};

export const environment = {  
      production: false,
      apiUrl: "dev_Url"
    };

Upvotes: 0

Related Questions