问题
My current url is http://localhost:4200/test/dashboard.
I want to print base url i.e http://localhost:4200 using angular 5 features.
回答1:
No need for angular specific features, window.location.origin
will do it for you.
回答2:
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);
}
回答3:
console.log(location);
console.log(location.href);
to get base url : console.log(location.origin);
回答4:
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;
}
回答5:
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
}
}
回答6:
You can Try (Can Get all Detail of current location)
import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
@Component({
selector: 'some-component',
templateUrl: './component.html',
styleUrls: ['./component.scss']
})
export class SomeComponent implements OnInit {
constructor(location: Location) {}
ngOnInit() {
console.log(this.location._platformStrategy._platformLocation.location);
}
}
回答7:
I have used location from Rotemya's answer like this
import { Location } from '@angular/common';
constructor(public location: Location) { }
But this.location.origin didn't work for me. So I have used this.location.path.name
ngOnInit() {
console.log(this.location.path.name);
}
来源:https://stackoverflow.com/questions/51984268/how-to-get-base-url-in-angular-5