如何使用angular2的http与应用程序主机端口之外的其他端口? [英] How to use angular2's http with other port than application host port?

查看:110
本文介绍了如何使用angular2的http与应用程序主机端口之外的其他端口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET解决方案,包含一个托管我的angular2应用程序的web项目和一个web api项目。

I have a ASP.NET solution with both a web project that hosts my angular2 app and a web api project.

这两个项目都设置为启动项目,并且是在不同的端口上运行( 45365 用于Web项目, 20234 用于web api项目)。

Both projects are setup as startup projects and are running on different ports (45365 for the web project and 20234 for the web api project).

假设我有一个公开 / api / values 的网络API控制器,目前可通过访问http:// localhost:20234 / api / values

Let´s say I have a web api controller that exposes /api/values which is currently accessible via http://localhost:20234/api/values

如何在angular2 web应用程序中访问它?如果我尝试

How can I access this in my angular2 web app? If I try

this.http.get("api/values")

它试图访问 http:// localhost:45365 / api / values 这是不希望的。但是,我希望它调用 http:// localhost:20234 / api / values 而不指定包含域的整个URL以使我的服务工作即使应用程序发布到公共服务器,其他域不是 localhost

it tries to access http://localhost:45365/api/values which is not desired. However, I want it to call http://localhost:20234/api/values without specifying the whole url including domain to make my service work even when the app is published to a public server with an other domain than localhost.

如何判断 http。 get()使用 20234 作为端口号?

How do I tell http.get()to use 20234 as port number?

推荐答案

constructor(private location:Location, private locationStrategy:LocationStrategy) {}

someMethod() {
  var base = this.locationStrategy.getBaseHref();
  // replace port

  this.location.prepareExternalUrl(base + 'xxx');
}

您可以在转发到的服务中实现此功能Http 所以你不需要重复它。

You can implement this in a service that forwards to Http so you don't need to repeat it.

(未测试)

这篇关于如何使用angular2的http与应用程序主机端口之外的其他端口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆