繁体   English   中英

如何检测角度 2 中的 URL 变化?

[英]How to detect URL change in angular 2?

可以使用router.events流检测路由更改。 如何检测 Angular 2 中的路线变化? )。

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

您可以注入Location并订阅它

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

...

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

正如哈利提到的。 这仅通知有关 popState 事件(路由器或更改 URL 的类似代码)

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM