简体   繁体   中英

Environment specific service endpoint in angular2 with angular-cli

I am uning angular-cli for my angular2 project.

I am calling backend ajax services through my angular2 service.

I have different services end point (URL) for different task. I want to make those services environment sensetive.

Suppose I have two service

  1. Customer Service : https://localhost:8080/customers
  2. Product Service : https://localhost:8080/products

Since localhost is avaliable in my development environment. It is working

Now suppose xxxx is my production web service host ip address.

So for production environment the service URL will be https://xxxx:8080/customers

Please help me how to achive this.

I found there is a block in angular-cli.json file as

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

But I did now found that environments directory.

How to create that and manage environment specific end points?

The command ng new PROJECT_NAME was supposed to create both files:

  • src/environments/environment.prod.ts
  • src/environments/environment.ts

I believe you can create it manually. Here is the generated code:

// 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`.

export const environment = {
  production: false
};

You can add the configuration you need in both files for the respectful environment:

// src/environments/environment.ts
export const environment = {
  production: false,
  apiUrl: 'http://localhost:8080'
};

...

// src/environments/environment.prod.ts
export const environment = {
  production: true,
  apiUrl: 'https://x.x.x.x'
};

To use the configuration just:

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

//...

let url = `${environment.apiUrl}/customers`;

Just make sure you are importing '../environments/environment' and NOT '../environments/environment.prod'.

You can declare your variables in environment files like that:
process.env.apiHost = "http://myhostfordevorprod"
You should put that before export in your environment file:
export const environment = { production: false, //or true };
and access it in your component like this:
my_var = process.env.apiHost
Then you run ng build --environment=production or ng build --environment=development to choose which environment file to load. Instead build you could also run ng serve --environment=development

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