方法一:通过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 这个文件,用于配置后台请求地址了


本文介绍了在Angular应用中动态设置后台请求地址的两种方式:一是通过在assets目录下放置config.js文件,利用window对象获取配置;二是程序运行时通过http请求assets目录下的文本文件来加载配置。这两种方法确保了打包后的应用能正确获取服务器地址。
https://www.yuque.com/wuzhiwei-rrcdf/dzn2b9/cvghz4

1940

被折叠的 条评论
为什么被折叠?



