Как получить базовый url в угловой 5? - программирование
Подтвердить что ты не робот

Как получить базовый url в угловой 5?

Мой текущий URL-адрес http://localhost: 4200/test/dashboard.

Я хочу напечатать базовый URL, т.е. http://localhost: 4200, используя угловые 5 функций.

4b9b3361

Ответ 1

console.log (местоположение);

console.log(location.href);

получить базовый url: console.log(location.origin);

Ответ 2

Нет необходимости в угловых конкретных функциях, window.location.origin сделает это за вас.

Ответ 3

PlatformLocation предоставляет более подробную информацию о 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);
}

Ответ 4

Вы можете импортировать "Местоположение" из пакета "common":

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
  }

}

Ответ 5

Вы можете попробовать (можете получить все детали текущего местоположения)

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);  
    }
}

Ответ 6

Я использовал местоположение от Rotemya, ответь так

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

constructor(public location: Location) { }

Но this.location.origin не работает для меня. Поэтому я использовал this.location.path.name

 ngOnInit() {
        console.log(this.location.path.name);
  }

Ответ 7

Это не работает для меня (Angular 7):

this.location.path.name

Но я обнаружил, что это можно получить из документа:

import { Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

constructor(@Inject(DOCUMENT) private document: Document) {
    const origin = this.document.location.origin;
}