【发布时间】:2017-01-26 19:26:34
【问题描述】:
快速版本 - 我相信我想要的:
如何配置angular2 http 服务以忽略<base href>
更长的版本 - 如果有更好的方法: 在我的项目中,我们使用 Apache 为两个 Angular 应用程序提供服务:
http://host/index.html - angular 1
http://host/ng2/index.html - angular 2
它们都使用相同的端点
http://host/api/foo
两个应用都使用同一个虚拟主机。 angular 2 应用位于磁盘上的 public/ng2 下。
问题归结为:
当我使用:<base href="/ng2/"> 时,角度应用程序加载正常。
但是所有使用 http 服务的 api 请求都会被污染。
http.get('/api/foo/2') goes to http://host/ng2/api/foo
我目前的解决方案是将base href 设置为<base href="/">,并将除index.html 之外的所有angular2 文件直接放在/public 下。 (index.html 仍在 /public/ng2 中)这可行,但它是一团糟。
我想要什么:
- 所有 angular2 文件都在 /public/ng2 中(由于
<base href="/ng2/">或其他 Apache 配置而有效) - 传出请求没有附加 ng2。
- 例如 http.get('/api/foo/2') => http://host/api/foo
不能硬编码网址
【问题讨论】:
-
我建议使用 $config 变量,其中包含用于 HTTP 调用的 API 的完整基本 URL,并像这样使用 http:
http.get(api_root + '/foo/2') -
感谢@KiJéy。我忘了提到的是我们部署了多个实例。每个都有自己的 /api/foo/2。例如。 (customer1-host/api/foo 和 customer2-host/api/foo)。所以相对路径会好很多。
-
您能解释一下为什么您认为相对路径会更好吗?我同意@KiJéy,将 URL 放入环境文件并使用绝对路径。
-
我上面描述的问题肯定可以使用绝对路径来解决。当我写这个问题时,我从未认真考虑过以编程方式创建绝对路径的选项。例如 fullUrl = document.location.protocol + "//" + document.location.host + "/" + relativeUrl。这种方法确实有效 - 谢谢!
标签: apache angular angular-cli