问题描述
如何在Angular 2 CLI项目中为开发和生产环境声明2个不同的代理URL?例如,在开发模式下,我想使用
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
{
"/api/*": {
"target": "http://localhost:3000",
"secure": false
}
}
但在生产模式下,我将使用
but in production mode, I will use
{
"/api/*": {
"target": "http://api.exampledomain.com",
"secure": false
}
}
推荐答案
我不认为您可以通过环境文件控制代理功能.一种替代方法是在环境文件中定义您的api域
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'
}
然后在您的ts源文件中将域从环境文件中拉出
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');
}
}
现在,当您运行构建或服务命令时,它们将使用环境文件中定义的api路径
now when you run your build or serve commands they will use the api path defined in the environment file
这篇关于Angular 2 CLI中基于环境的不同代理配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!