Different proxy config based on environment in Angular 2 CLI

后端 未结 2 761
北恋
北恋 2021-01-02 14:49

How can I declare 2 different proxy URLs for development and production environments in Angular 2 CLI project? For example, while in development mode, I would like to use

2条回答
  •  醉梦人生
    2021-01-02 15:14

    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

提交回复
热议问题