Angular 实现动态配置后端请求地址

方法一:通过JS方法配置

1.因为angular 在打包代码时只有资源目录是不被编译的,所以我们通过在在资源目录放入配置文件 assets/config.js 。 代码如下

(function(v, p) {
  window[v] = p;
})('getWinConfig', function(){
  delete window.getWinConfig
  /**
   * 外置配置参数
   */
  /*
   * service: 服务器请求地址
   */
  return {
    server: "http://192.168.12.25:8001/platform/"
  }
})

2.然后在 environments/environment.prod.ts 和environments/environment.ts 编写如下代码

environments/environment.prod.ts

export const environment = {
  production: true,
  config: {
    // @ts-ignore
    server_url: window.getWinConfig().server
  }
};

environments/environment.ts 

// This file can be replaced during build by using the `fileReplacements` array.
// `ng build --prod` replaces `environment.ts` with `environment.prod.ts`.
// The list of file replacements can be found in `angular.json`.

export const environment = {
  production: false,
  config: {
    // server_url: window.getWinConfig().server
    server_url: "http://192.168.12.25:8001/platform/"
  }
};

/*
 * For easier debugging in development mode, you can import the following file
 * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
 *
 * This import should be commented out in production mode because it will have a negative impact
 * on performance if an error is thrown.
 */
// import 'zone.js/dist/zone-error';  // Included with Angular CLI.

3.通过 ng build 打包后,assets目录下就会存在 config.js 这个文件,用于配置后台请求地址了

 方法二:在程序代码中通过http请求assests目录下的文本文件,实现后台请求地址的加载

登录 · 语雀十万阿里人都在用的笔记与文档知识库,面向企业、组织或个人,提供全新的体系化知识管理,打造轻松流畅的工作协同。金融级数据安全、丰富的应用场景、强大的知识创作与管理,助力企业、个人轻松拥有云端知识库https://www.yuque.com/wuzhiwei-rrcdf/dzn2b9/cvghz4参考我在语雀写的文章

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
>