How to use angular2's http with other port tha

2019-05-06 12:20发布

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

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).

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

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

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

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.

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

1条回答
等我变得足够好
2楼-- · 2019-05-06 12:52
constructor(private location:Location, private locationStrategy:LocationStrategy) {}

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

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

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

(not tested)

查看更多
登录 后发表回答