Как вызвать событие Javascript при изменении URL - PullRequest
0 голосов
/ 28 января 2019

В настоящее время я имею дело с угловым проектом, мне нужно вызвать событие при изменении маршрутизации / изменении URL с одной страницы на другую (так как это угловая страница проекта, которая не будет обновлена).

Я пытался с различными сценариями на странице index.html, как показано ниже:

  window.onbeforeunload = function () {
   //not fit;
  });

    window.onhashchange = function () {
    //not fit;
   });

Можем ли мы иметь какие-либо другие решения для запуска события при изменении URL (я не хочу использовать слушателей в angular).

1 Ответ

0 голосов
/ 28 января 2019

Вы можете сделать это, внедрив hashchange даже в window

И если вы используете jQuery, этот плагин может вам помочь.

Или в вашем случае проверьте чистый код JS

function hashHandler() {
    this.oldHash = window.location.hash;
    this.Check;

    var that = this;
    var detect = function() {
        if(that.oldHash != window.location.hash) {
            alert("HASH CHANGED - new has" + window.location.hash);
            that.oldHash = window.location.hash;
        }
    };

    this.Check = setInterval(function() { detect() }, 100);
}

var hashDetection = new hashHandler();

Пример чистого демо-кода для angular с маршрутизатором:

import { Component, OnInit } from '@angular/core'; // I import Location so that I can query the current path
import { Location } from '@angular/common'; // I also import Router so that I can subscribe to events
import { Router } from '@angular/router'; 

@Component(
{ selector: 'app-top-nav', 
  templateUrl: './top-nav.component.html', 
  styleUrls: ['./top-nav.component.scss'] }
)
export class TopNavComponent implements OnInit { 
    route: string; 

    constructor(location: Location, router: Router) { // within our  constructor we can define our subscription
       // and then decide what to do when this event is triggered.
       // in this case I simply update my route string.
       router.events.subscribe((val) => { if(location.path() != '') { this.route = location.path(); } else { this.route = 'Home' } }); 
    } 

    ngOnInit() { 
    } 
} 

Приведенный выше код должен работать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...