Подтвердить что ты не робот

Angular 2 Получить текущий маршрут

Поэтому мне нужно как-то проверить, есть ли я на домашней странице и что-то делать, а на других страницах этого не делают. Также этот компонент импортируется на всех страницах.

Как я могу обнаружить на этом компоненте, если я на главной странице???

Спасибо

4b9b3361

Ответ 1

Попробуйте это,

import { Router } from '@angular/router';
export class MyComponent implements OnInit {

    constructor(private router:Router) { ... }

    ngOnInit() {
        let currentUrl = this.router.url; /// this will give you current url

        // your logic to know if its my home page.
    }

}

Ответ 2

Попробуйте

import { Component } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';

@Component({...})

export class MyComponent {

  constructor(private router:Router) {

    router.events.subscribe(event => {

      if (event instanceof NavigationEnd ) {
        console.log("current url",event.url); // event.url has current url
        // your code will goes here
      }
    });
  }
}

Ответ 3

Попробуйте любой из них из родного объекта окна.

console.log('URL:' + window.location.href);
console.log('Path:' + window.location.pathname);
console.log('Host:' + window.location.host);
console.log('Hostname:' + window.location.hostname);
console.log('Origin:' + window.location.origin);
console.log('Port:' + window.location.port);
console.log('Search String:' + window.location.search);

ПРИМЕЧАНИЕ: НЕ ИСПОЛЬЗУЙТЕ ЭТО В СЕРВЕРЕ

Ответ 4

Если вам нужен полный URL, используйте экземпляр LOCATION следующим образом: -

([Location][1])location.href = https://test-mydomain.com/#/securelogin?name=batman

& если вы хотите относительный URL, используйте следующий экземпляр ROUTER: -

this.router.url = securelogin?name=batman

Следуйте приведенному ниже фрагменту на основе углового 4: -

constructor( private router: Router) {
  console.log(this.router.url);
/**
* securelogin?name=batman
*/

  console.log(location.href);
/**
* https://test-mydomain.com/#/securelogin?name=batman
*/
}

Ответ 5

Я собирался ответить на этот вопрос, но у меня есть тот же ответ с BigBrother. Этот ответ предназначен для тех, кто использует "#" в своем URL-адресе, так как он возвращает только "/" в некотором коде местоположения маршрутизатора.

Это пример кода одного из моих проектов:

this.router.events.subscribe((event)  => {
  if(event instanceof NavigationEnd) {
      this.currentPage =  event.url;
      if ( event.url != '/admin') {
        setTimeout(()=>{
            this.modalRef = this.modalService.show(ModalSurveyComponent,this.config);
        }, 3000);
      }
  }
});

Так что всплывающее окно покажет только если текущий маршрут не "/admin"

Ответ 6

Вы можете использовать Angular Location Service.

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

Вы можете получить доступ к пути, используя:

location.path();

Ответ 7

import { RouterStateSnapshot } from '@angular/router';

constructor(private state: RouterStateSnapshot) {
    console.log("Current Url Path", state);
}