Setting Base Href Dynamically in Angular 6

Anand Shende
2 min readOct 17, 2018

--

Article Content

  1. Angular 6

Repo — https://github.com/anandshende/webpackProxy.git

This story is a continuation of the Webpack Proxy story, which contains the initial configurations and lays the infrastructure for this story.

Brief Intro To Base Href

Base Href is used to set a base path for all your requests made relatively, the relative path is appended to this base path. For example,

/// index.html
<base href="/web/">
/// index.js
xmlHttp.open('GET', 'example');

When the above code has executed, the browser adds the relative path example to the base path /web/ to form /web/example/. It plays no role if an absolute path is provided.

What is the need to set base href dynamically

If the base application URL is dynamic, such as an inclusion ofuserId in the base path. We cannot set the base path with the userId because it is variable and will surely change per user.

My Scenario

There is an application which is served at /web/ . We do not have to disturb the running application, there is another application which needs to return userInfo when the URL /web/userInfo/:id is opened in the browser. The userInfo component is a common component(let’s call this component userInfoComponent).

Code Changes

Index.html

<script>
window['base-href'] = window.location.pathname;
console.log(window['base-href']);
</script>

User-Info Module

@NgModule({
imports: [BrowserModule],
declarations: [UserInfoComponent],
bootstrap: [UserInfoComponent],
providers: [
{
provide: APP_BASE_HREF,
useValue: window['base-href']

}
],
})

The base-href property from the window object is set in HTML and accessed in the module (root module). This updates the base-href , and hence we can now request using relative paths.

Try opening both applications. This solved my issue, hope it helps you all as well :)

--

--