简体   繁体   中英

Angular sandbox application read browser URL

Currently, I'm working on reading URL from the browser and assigning that as global URL, instead of hardcoding the base_url I need it to be read from the browser and patch that to the all the service with the URL. I have tried doing this and this code works but the problem is once the screen is reloaded all the APIs are going to fail.

CODE

 setTimeout(() => {
     if (environment.production) {
         base_url = window.location.origin + '/APPLICATION/resources/';
     }else {
        base_url = 'http://106.51.66.219:1234/APPLICATION/resources/' ;
     }
 }, 1000);

is there any better way to set the base_url and it works flawlessly even after clicking of the refresh.

As your using angularjs, you can try $location service to get URL from browser as below and this will work as well when reload the page

setTimeout(() => {
 if (environment.production) {
     base_url = $location.protocol()+'//'+$location.host() + '/APPLICATION/resources/';
 }else {
    base_url = 'http://106.51.66.219:1234/APPLICATION/resources/' ;
 }
}, 1000);

and If in production have port in url then have to write some condition to join port ($location.port()) in url

Two things:

  1. Never expose such configurations to the client. In the production version, people can see your dev endpoint . Try and move such configurations as much as possible to your build/bundling system.

  2. It's a good idea to define all such constants in a service or a constants.ts file. As pointed out by @plalx

You can use standard JS here:

window.location.href

But you rather want to use the Angular route for that:

constructor(route: ActivatedRoute) {
    const url: Observable<string> = route.url.map(segments => segments.join(''));
    url.subscribe((url) => console.log(url));
}

See: https://angular.io/api/router/ActivatedRoute

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM