Environment specific service endpoint in angular2

2020-03-26 08:03发布

问题:

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 x.x.x.x is my production web service host ip address.

So for production environment the service URL will be https://x.x.x.x: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?

回答1:

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



回答2:

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