Angular base href for web, desktop, mobile ( and paths for services)
My current stack is .NET Core (backend) + Angular ( frontend) ( For database, it is usual SqlServer – but I use Sqlite, Mongo, local storage ….)
With Angular I can have Mobile application ( by Cordova ) and Windows Desktop ( with Electron)
But the BaseHref it is a PIA …. even for Web, if you host into a virtual directory .
So this is my setup in 2 steps. Maybe could be somehow easy, but… I did not discover something better yet.
Step 1: Create a favicon.svg into the assets folder
Step 2: Instead of
<base href=”/”>
put
<!– <base href=”/”> –>
<script>
var isCordovaApp = !!window.cordova;
var isWindowApp = !!window.MSApp;
if (isCordovaApp) {
hrefApp = “.”;
}
if (isWindowApp) {
hrefApp = “./”;
}
if (!(isCordovaApp || isWindowApp)) {
var baseHref = window.location.href.split(“/”);
while (true) {
baseHref.pop();
hrefApp = baseHref.join(“/”) + “/”;
// window.alert(hrefApp);
var request = new XMLHttpRequest();
request.open(“GET”, hrefApp + “favicon.svg”, false); request.send(null);
if (request.status === 200) {
if(request.responseText.indexOf(“meta name=”)<1){
console.log(`found ${hrefApp} `);
break;
}
}
}
}
document.write(‘<base href=”‘ + hrefApp+ ‘” />’);
</script>
And this is all!
For correct path of services , I do this
For each service , I construct with
constructor(@(Inject)(APP_BASE_HREF) baseHref: string, private client: HttpClient)
this.baseUrl = environment.webAPIUrl + baseHref ;
and when I call a function
const url = this.baseUrl+’api/WeatherForecast;
In the envoronment.ts I have
export const environment = {
production: false,
webAPIUrl: ‘http://localhost:5000’
};
and in the environment.prod.ts I do have
export const environment = {
production: true,
webAPIUrl: ”
};
One more thing: to inject APP_BASE_HREF , I must have into app.modue.ts
providers: [{
provide: APP_BASE_HREF,
useFactory: (s: PlatformLocation) => s.getBaseHrefFromDOM(),
deps: [PlatformLocation]
}
That’s all! ( yes , I know it is a bit complicated….)
Leave a Reply