使用base href时请求url问题

alf*_*han 6 apache angular-cli angular

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

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

http://host/index.html - angular 1
http://host/ng2/index.html - angular 2
Run Code Online (Sandbox Code Playgroud)

他们都使用相同的端点

http://host/api/foo
Run Code Online (Sandbox Code Playgroud)

两个应用程序都使用相同的虚拟主机。Angular 2 应用程序位于磁盘上的 public/ng2 下。

问题归结为:

当我使用时:<base href="/ng2/">角度应用程序加载良好。然而,所有使用 http 服务对 api 的请求都会受到污染。

http.get('/api/foo/2') goes to http://host/ng2/api/foo
Run Code Online (Sandbox Code Playgroud)

我当前的解决方案是将base href设置为<base href="/">并将除index.html之外的所有Angular2文件直接放在/public下。(index.html 仍在 /public/ng2 中)这可以工作,但很混乱。

我想要什么:

  • 所有 angular2 文件都位于 /public/ng2 中(由于<base href="/ng2/">或其他 Apache 配置而有效)
  • 传出请求不会附加 ng2。

无法对 url 进行硬编码

Imt*_*que 5

简单地附加'/'到 api 调用将停止附加值baseHref

  getFoo(): Observable<any> {
    const url = '/' + 'api/foo';
    return this.http.get<any>(url);
  }
Run Code Online (Sandbox Code Playgroud)


alf*_*han 4

最后我按照 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))...
  }
Run Code Online (Sandbox Code Playgroud)