My current url is http://localhost:4200/test/dashboard.
I want to print base url i.e http://localhost:4200 using angular 5 features.
This doesn't work for me (Angular 7):
this.location.path.name
But I found that it's possible to get it from document:
import { Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
constructor(@Inject(DOCUMENT) private document: Document) {
const origin = this.document.location.origin;
}
PlatformLocation provides more details about the URL:
import {PlatformLocation } from '@angular/common';
constructor(platformLocation: PlatformLocation) {
console.log((platformLocation as any).location);
console.log((platformLocation as any).location.href);
console.log((platformLocation as any).location.origin);
}
You can import 'Location' from the 'common' package:
import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common'; // <--- Here
import { Router } from '@angular/router';
@Component({
selector: 'some-component',
templateUrl: './component.html',
styleUrls: ['./component.scss']
})
export class SomeComponent implements OnInit {
constructor(location: Location) {}
ngOnInit() {
console.log(this.location.origin); // <--- Use Here
}
}