Search code examples
angularangular-router

How to get base url along with path in angular 5?


My current url is http://localhost:4200/myApp/dashboard.

I want to print base url i.e http://localhost:4200/myApp using angular 5 features.

I am using this code:

constructor(private platformLocation: PlatformLocation) {
}

const appPath = (this.platformLocation as any).location.origin

however it returns only domain name http://localhost:4200


Solution

  • Added base_href value in app module providers

    import { APP_BASE_HREF } from '@angular/common';
    
    providers: [
        { provide: APP_BASE_HREF, useValue: "http://localhost:4500/MyApp" }
    ]
    

    and in the code

    import { LocationStrategy, Location } from '@angular/common';
    
    constructor(private locationStrategy: LocationStrategy) {}
    const appPath = location.origin + this.locationStrategy.getBaseHref();
    

    Fiddle: https://stackblitz.com/edit/angular-router-basic-example-rqcji3?file=app%2Fapp.component.ts