I have an Angular 2 app that will be installed on multiple servers, and needs to access a backend that is also on multiple servers. I'm using the code from this answer, specifically the edit that works with methods other than GET, and it works well if I hardcode the backend URL.
For a given frontend server, the backend it needs to access will always be the same. For example, if the frontend is on "example.com", the backend will always be on "example.com:9080".
I can bundle the app for each different server, changing "localhost:9080" in that answer to "example1.com:9080", "example2.com:9080", etc. as appropriate. This would mean having to make code changes and bundle the app for each server.
Is there a way that I can somehow fetch the URL that I need to access for the backend so I can bundle it once and deploy it to all the servers?
I'm using Angular 2.4.5 and serving the frontend using Apache.
Your really do not want to have this in your application. This should be configuration as it depends on the server you're on (in other words, you don't want to have to change your code and rebuild when you add a server at a later point). Therefore, my guess is that you really want to solve this on your apache server. You can consider using ProxyPass and ProxyPassReverse (in httpd.conf or htaccess). That way you don't have to bother worrying about it in your application as there, you would only use relative paths to your api endpoints.
For example, suppose you have your angular app served from example.com, and your backend api lives at example.com:9080/api/.
Your code would simply use /api as the path to your endpoints and the ProxyPass would rewrite those to the backend using:
ProxyPass /api example.com:9080
ProxyPassReverse /api example.com:9080
You would need MOD_PROXY installed (pretty common on most hosts): https://httpd.apache.org/docs/current/mod/mod_proxy.html