Search code examples
angularlazy-loadingangular4-router

Angular 4 Routing - base-href gets prepended to hashPath


When the built version of the angular app is placed in the root, it generates the url just fine

http://thisismydomain.com/#/master/data-source-management/data-sources/list

But when it is placed somewhere deeper inside the root, and I use base-href, the router still behaves fine while loading the page, but once it is loaded, the base-href gets prepended to the hashpath like the following:

http://thisismydomain.com/deeper/inside/#/deeper/inside/master/data-source-management/data-sources/list

Expected Url:

http://thisismydomain.com/deeper/inside/#/master/data-source-management/data-sources/list

I found out the problem was associated with the injection of APP_BASE_HREF entry in the import section of app.module.ts?

providers: [
AuthenticationService,
KaribaService,
GlobalService,
NotificationService,
/*
{
  provide: APP_BASE_HREF,
  useFactory: getBaseHref,
  deps: [PlatformLocation]
},
*/
CustomizationService

]

Commenting that out solves the problem, but I need it in order to inject BASE_HREF in my services to pull contents from assets folder. HELP?

P.S. I am using lazy loading.


Solution

  • I resolved it by creating a CustomLocationStrategy by extending the HashLocationStrategy, since this seemed to be the only solution.

    import {Injectable} from '@angular/core';
    import {HashLocationStrategy} from "@angular/common";
    
    @Injectable()    
    export class CustomLocationStrategy extends HashLocationStrategy {
    
      prepareExternalUrl(internal: string): string {
        const url = this.getBaseHref() + '#' + internal;
        return url;
      }
    }
    

    Imported the custom class along with APP_BASE_HREF and LocationStrategy in app.module.ts

    import { APP_BASE_HREF, LocationStrategy } from "@angular/common";
    import { CustomLocationStrategy } from './common/services/customLocationStrategy.service';
    

    and added the following in the providers section.

    providers: [
      {
        provide: APP_BASE_HREF, 
        useValue: window.location.pathname
      }, 
      {
        provide: LocationStrategy, 
        useClass: CustomLocationStrategy
      }
    ]