【问题标题】:How to detect URL change in angular 2?如何检测 Angular 2 中的 URL 变化?
【发布时间】:2017-02-15 21:44:35
【问题描述】:

可以使用router.events 流检测路线变化。 (How to detect a route change in Angular 2?)。

但我不确定如何检测浏览器 URL 更改。

【问题讨论】:

  • 浏览器 URL 变化只能由 2 个因素引起:Angular2 内部的路由变化或用户手动输入新 URL。您可以订阅前者。后者将重新加载整个应用程序并检测它是没有意义的。
  • 感谢您的评论。后一种情况也可能来自用户单击其他外部 URL,或单击浏览器的书签栏。在我的应用程序中,我需要捕捉到这一点,以便向用户显示未保存的更改确认对话框。

标签: javascript angular angular2-routing


【解决方案1】:

你可以注入Location并订阅它

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

...

constructor(location:Location) {
  location.subscribe(val => console.log(val));
}

正如哈利所说。这仅通知 popState 事件(路由器或类似代码更改 URL)

【讨论】:

  • 谢谢。因此,没有任何内置方法可以捕获所有 URL 更改。不喜欢:$rootScope.$on('$stateChangeStart', () => {...}) 角度 1
  • Property 'subscribe' does not exist on type 'Location'.
  • AFAIR 已更改。 BrowserLocation 有,但已设为私有。 developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/… 应该可以工作,或者如果您使用 Angular 路由器,它也允许订阅更改(请参阅问题中的链接)。
  • 我收到“属性订阅不存在..”因为我错过了正确的导入:import {Location} from '@angular/common';
【解决方案2】:

注入Location 并使用onUrlChange 事件监听器:

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

constructor(private location: Location) {
  location.onUrlChange(url => console.log(url));
}

【讨论】:

    【解决方案3】:

    您可以像这样从根文件订阅路由器事件

    constructor(private router: Router,
              private aRouter: ActivatedRoute) {
    this.router.events.pipe(filter(e => e instanceof NavigationEnd))
    .subscribe((s: NavigationEnd) => {
      //write your logic here
       console.log(s);
    });
    }
    

    【讨论】:

      猜你喜欢
      • 2017-05-04
      • 2017-02-09
      • 1970-01-01
      • 1970-01-01
      • 2017-08-15
      • 1970-01-01
      • 2019-06-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多