使用base href时请求url问题

时间:2017-01-26 19:26:35

标签: apache angular angular-cli

快速版 - 我相信我想要的东西: 如何配置angular2 http服务以忽略<base href>

更长的版本 - 如果有更好的方法: 在我的项目中,我们使用Apache提供两个角度应用程序:

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。

不能对网址进行硬编码

2 个答案:

答案 0 :(得分:1)

最后我做了Ki Jey的建议并使用绝对URL来获取API。

service.base.ts: 
protected getAbsoluteUrl(relativeUrl : String) : String { 
  return document.location.protocol + "//" + document.location.host + "/" + relativeUrl
}

service.ts:
class service extends BaseService
  getTheFoo(){ 
    http.get(this.getAbsoluteUrl(foo/2))...
  }

答案 1 :(得分:1)

仅将'/'附加到api调用将停止附加baseHref的值。

  getFoo(): Observable<any> {
    const url = '/' + 'api/foo';
    return this.http.get<any>(url);
  }
相关问题