For running an angular app on a sub path there is the compiler option base-href.
But it doesn't work with http-server as expected. It results in an double sub path or inexplicable redirect.
Simple steps to reproduce are as follows:
Create new routing app on command line (angular 14) by
ng new myapp– routing IS NEEDED – and enter directorymyapp/.Remove the unused files
app.component.htmlandapp.component.css.Replace the content of your
app.component.tsby the following dummy content:import { Component } from '@angular/core' @Component({ selector: 'app-root', template: `<img src="favicon.ico" alt="icon" />` }) export class AppComponent { constructor() { // @Inject(APP_BASE_HREF) readonly unnecessary: string } }Install
http-serverbynpm i http-server -D.Make a build by
ng build --base-href myapp.Start the app by http-server:
./node_modules/.bin/http-server -p 8080 -c-1 dist/and enterhttp://localhost:8080/myapp/. The app redirects tohttp://localhost:8080/myapp/myapp/. I have a double sub path. Without routing module this doesn't happen.
Finally I found out that the usage of the
APP_BASE_HREFDI token avoids this redirect. Leading/of/myappis necessary.... @NgModule({ ... providers: [{ provide: APP_BASE_HREF, useValue: '/myapp' }], ... }) export class AppModule { }
Could anyone explain this behavior and what the compiler-option --base-href and the DI token APP_BASE_HREF does?
used package.json
{
"name": "myapp",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
"private": true,
"dependencies": {
"@angular/animations": "^14.0.0",
"@angular/common": "^14.0.0",
"@angular/compiler": "^14.0.0",
"@angular/core": "^14.0.0",
"@angular/forms": "^14.0.0",
"@angular/platform-browser": "^14.0.0",
"@angular/platform-browser-dynamic": "^14.0.0",
"@angular/router": "^14.0.0",
"@angular/service-worker": "^14.0.0",
"rxjs": "~7.5.0",
"tslib": "^2.3.0",
"zone.js": "~0.11.4"
},
"devDependencies": {
"@angular-devkit/build-angular": "^14.0.2",
"@angular/cli": "~14.0.2",
"@angular/compiler-cli": "^14.0.0",
"@types/jasmine": "~4.0.0",
"http-server": "^14.1.1",
"jasmine-core": "~4.1.0",
"karma": "~6.3.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.0.0",
"karma-jasmine-html-reporter": "~1.7.0",
"typescript": "~4.7.2"
}
}
