How to use angular2 http with a different port than the application host port?

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

Both projects are configured as launch projects and work on different ports ( 45365for a web project and 20234for a web api project).

Suppose I have a web api controller that provides /api/values, which is currently available throughhttp://localhost:20234/api/values

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

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

he is trying to access http://localhost:45365/api/valuesthat which is undesirable. However, I want it to call http://localhost:20234/api/valueswithout specifying the entire URL, including the domain, so that my service works even when the application is published on a public server with a different domain than localhost.

How to report http.get()use 20234as port number?

+4
source share
1 answer
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 is sent to Http, so you do not need to repeat it.

(not verified)

+5
source

All Articles