Angular:全局声明目标域/IP

时间:2021-05-18 10:10:14

标签: angular

我正在开发一个应用程序并向后端服务器发送 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);
})

我的问题是,有没有什么方法可以像在 angular.json 文件中那样在项目中的某个地方全局声明域/IP,以便每个 Angular 组件都可以使用它?

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

2 个答案:

答案 0 :(得分:1)

你可以使用src/environments/environment.ts & src/environments/environment.prod.ts。在 angular.json 你有用 env.prod.ts 替换 env.ts 的设置

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

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

答案 1 :(得分:1)

为此目的使用src/environments/environment.ts

在 environment.ts 中定义您的配置

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

在任何你想要的地方导入 environment.ts 并像下面一样使用它

import {environment} from '../../../environments/environment';
    
this.http.post(`http://${environment.serverIp}:3000/api/login`, form.value, {responseType: "text"})
      .subscribe(responseData => {
         console.log(responseData);
    }) 
相关问题