Unexpected behavior of "base-href" with a angular routing app

Viewed 72

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:

  1. Create new routing app on command line (angular 14) by ng new myapprouting IS NEEDED – and enter directory myapp/.

  2. Remove the unused files app.component.html and app.component.css.

  3. Replace the content of your app.component.ts by 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
        }
    }
    
  4. Install http-server by npm i http-server -D.

  5. Make a build by ng build --base-href myapp.

  6. Start the app by http-server: ./node_modules/.bin/http-server -p 8080 -c-1 dist/ and enter http://localhost:8080/myapp/. The app redirects to http://localhost:8080/myapp/myapp/. I have a double sub path. Without routing module this doesn't happen.

enter image description here

  1. Finally I found out that the usage of the APP_BASE_HREF DI token avoids this redirect. Leading / of /myapp is 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"
  }
}
0 Answers
Related