Nitin S
Nitin S

Reputation: 7591

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

Upvotes: 1

Views: 10213

Answers (5)

FXLima
FXLima

Reputation: 395

Try this way:

import {Location, LocationStrategy, PathLocationStrategy} from '@angular/common';
import {Component, Injector} from '@angular/core';

@Component({
  selector: 'path-location',
  providers: [Location, {provide: LocationStrategy, useClass: PathLocationStrategy}],
  template: `
    <h1>PathLocationStrategy</h1>
    Current URL is: <code>{{myLocation.path()}}</code><br>
    BaseHref is: <code>{{myLocation.getBaseHref()}}</code><br>
  `
})
export class PathLocationComponent {

  public myLocation: LocationStrategy;

  constructor(private injector: Injector) {

    /** Define i18n idioma do sistema */
    this.myLocation= this.injector.get(LocationStrategy);

    console.log('BaseHref: ' + this.myLocation.getBaseHref());
    console.log('Path: ' + this.myLocation.path());
  }
}

Based on: https://angular.io/api/common/Location#example

And: https://angular.io/api/common/LocationStrategy

Upvotes: 0

Felix
Felix

Reputation: 4595

Some other solution:

import { DOCUMENT, LocationStrategy } from '@angular/common';


@Injectable()
export class SomeService {
  constructor(@Inject(DOCUMENT) private readonly document: any,
    private readonly locationStrategy: LocationStrategy) {}

  // for localhost: http://localhost:4200/someBaseHref
  getUrl(): string {
    return `${this.document.location.origin}/${this.locationStrategy.getBaseHref()}`
  }

}

Upvotes: 0

Nitin S
Nitin S

Reputation: 7591

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

Upvotes: 1

marsibarsi
marsibarsi

Reputation: 1073

You can also use Location:

import:

import {Location} from '@angular/common';

Inject:

constructor(@Inject(Location) private readonly location: Location) {}

Use:

const pathAfterDomainName = this.location.path();

Upvotes: 3

Sachin Gupta
Sachin Gupta

Reputation: 5311

You can inject Router from @angular/router and use this.router.url

The baseHref should be available using this.router.location._baseHref

Upvotes: 2

Related Questions