Angular:全局声明目标域/IP



我正在开发一个应用程序,并向后端服务器发送HTTP请求。因为有很多组件,所以每次我想部署应用程序时,我都必须将localhost更改为目标域/IP。

this.http.post('http://localhost:3000/api/login', form.value, {responseType: "text"})
.subscribe(responseData => {
console.log(responseData);
})

在为生产模式构建它之前,我必须为每个HTTP请求做这样的事情:

this.http.post('http://IP.OF.THE.SERVER:3000/api/login', form.value, {responseType: "text"})
.subscribe(responseData => {
console.log(responseData);
})

或者,对于每个单独的组件来说都是这样

this.http.post(`http://${this.ipServer}:3000/api/login`, form.value, {responseType: "text"})
.subscribe(responseData => {
console.log(responseData);
})

我的问题是,有没有任何方法可以在项目中的某个地方全局声明域/IP,比如在angular.json文件中,这样每个angular组件都可以使用它?

我不想为此目的使用服务。如有任何帮助,我们将不胜感激。谢谢

u可以使用src/environment/environment.ts&src/environment/environment.products。在angular.json中,您有将env.ts替换为env.products 的设置

"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],

所以只需在每个文件中放入具有不同值的相同设置

为此使用src/environment/environment.ts

在环境中定义您的配置.ts

export const environment = {
production: false,
serverIp: 'localhost'
};

将环境.ts导入到您想要的任何位置,并像下面一样使用它

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

this.http.post(`http://${environment.serverIp}:3000/api/login`, form.value, {responseType: "text"})
.subscribe(responseData => {
console.log(responseData);
}) 

最新更新