4

In Angular CLI you can set custom port with the --port command, --port=4201 for example.

What I need to do is somehow get this port value so I can point to the correct server in my code but I'm unable to find such a way.

The reason for this is because if I use the default 4200 like this:

export const environment = {
  production: false,
  host: 'http://localhost:4200'
}

Then I won't be able to use --port without the code breaking.

Is this possible?

Chrillewoodz
  • 27,055
  • 21
  • 92
  • 175

3 Answers3

4

If you really want to have the environment config to point at the correct port at build time, you need to set up yourself a mecanism that'll get the correct port.

You could create your own run script (npm/sh/...), pass the port to that script. Then, that script will:

  1. Modify the port in the environment.ts file
  2. Start ng serve with the --port option

If you just want to use current host/port at runtime, you can just get it using

let host = `${window.location.protocol}//${window.location.host}`
David
  • 33,444
  • 11
  • 80
  • 118
2

You can get port number with following command:

window.location.port // it will give you port number

let url = `${window.location.protocol}//${window.location.hostname}`

// if port is specified in the url then it will be shown to you
if(window.location.port) {
  url += `:${window.location.port}`
}

let html = document.getElementById("portDiv")
html.innerHTML = url;
<div id="portDiv"></div>
WasiF
  • 26,101
  • 16
  • 120
  • 128
-1

If you are using following lines for changing port after your app start then it will not work.

export const environment = {
 production: false,
 host: 'http://localhost:4200'
}

But if you have .angular-cli.json file then change following lines to change port : { "defaults": { "serve": { "port": 8080 } } }

Amit Gaikwad
  • 516
  • 4
  • 12