Different proxy config based on environment in Angular 2 CLI

不羁岁月 提交于 2019-11-30 20:25:29

I do not believe you can control the proxy feature through the environment files. An alternative could be to define your api domains in your environment files

// environment.ts
export const environment = {
    production: false,
    api: 'http://localhost:3000'
};

// environment.prod.ts
export const environment = {
    production: true,
    api: 'http://api.exampledomain.com'
}

then in your ts source files pull the domain from the environment file

// some service
import { Injectable } from '@angular/core';
import { environment } from '../../../environment.ts';
import { Http } from '@angular/http';

@Injectable()
export class SomeService {
    constructor(private http: Http);

    getData(){
        return this.http.get(environment.api + '/rest-of-api');
    }
}

now when you run your build or serve commands they will use the api path defined in the environment file

in fact, you can do it, you just need to configure the router :

{
    "/api": {
        "target": "https://api.exampledomain.com",
        "secure": false,
        "logLevel": "debug",
        "router": {
          "localhost:4200" : "http://localhost:3000/exampledomain",
          "staging.exampledomain.com" : "http://api.staging.exampledomain.com"
        }
    }
}

What this do :

  • yout url match the proxy => will call the target defined
  • the host url match one router configuration => use the new target

For example :

I've deployed on localhost:4200 my angular app, when calling the url "api/callMeMaybe", then the router detect it and redirect in "http://localhost:3000/exampledomain".
If I've been on staging.exampledomain.com then the redirection will have be to "http://api.stagging.exampledomain.com".
Then, if none match, it keep the original target redirection.

Be careful, as order matters (the 1st match will be take)

Here is the documentation with an example

Edit

You can find the host value on your chrome debugger Network tab and selecting the api call, you get this details :

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!