I've seen this post about setting base href dynamically, but it's kind of pre-defined base href for each customer. In my case, I'd like to generate a random string as base href when a user accesses the web app. For example:
- When accessing http://localhost:4200 in browser, it redirects to :
http://localhost:4200/{random-string}/home
- When accessing http://localhost:4200/home, it also redirects to :
http://localhost:4200/{random-string}/home
- When accessing http://localhost:4200/{random-string}/home, it should just go as it is.
Understand that the base href can be set like this:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { APP_BASE_HREF, Location } from '@angular/common';
import { AppComponent } from './';
import { getBaseLocation } from './shared/common-functions.util';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
HttpModule,
],
bootstrap: [AppComponent],
providers: [
appRoutingProviders,
{
provide: APP_BASE_HREF,
useFactory: getBaseLocation,
deps: [MyService] // Updated based on @Yakov Fain's comment
},
]
})
export class AppModule { }
{random-string} should be generated in getBaseLocation function, but I need to save this {random-string} within the session for future use, so I saved the {random-string} to a shared service which is injected to the getBaseLocation like this:
export function getBaseLocation(globalService: MyService) {
let paths: string[] = location.pathname.split('/').splice(1, 1);
if (paths && paths[0]) {
// path contains the appId
console.log("Existing appId: " + paths[0]);
// Save appId for future use
globalService.applicationId = paths[0];
} else {
let newAppId = Math.random().toString(36).substr(2, 5);
// Save appId for future use
globalService.applicationId = newAppId;
}
let basePath = globalService.applicationId;
console.log("getBaseLocation : /" + basePath);
return '/' + basePath;
}
It works fine when accessing localhost:4200 which is redirected to localhost:4200/{random-string}/home. However, I received the error in browser console when clicking another link on the page or simply refreshing the current page. Error is like this:
GET http://localhost:4200/iun82/1.chunk.js 404 (Not Found)
ERROR Error: Uncaught (in promise): Error: Loading chunk 1 failed.
Error: Loading chunk 1 failed.
Please advise. Thanks!