【发布时间】:2018-03-12 21:41:01
【问题描述】:
Angular 4 中的 $locationChangeStart 等价物是什么?我正在寻找一个处理程序来跟踪 url 的变化。我读到有一个location service,但我不确定我是否需要使用它或在这里寻找一些东西https://angular.io/guide/router.. 任何指针都会很有帮助。谢谢!
更新:我想在服务而不是组件中执行此操作。
【问题讨论】:
Angular 4 中的 $locationChangeStart 等价物是什么?我正在寻找一个处理程序来跟踪 url 的变化。我读到有一个location service,但我不确定我是否需要使用它或在这里寻找一些东西https://angular.io/guide/router.. 任何指针都会很有帮助。谢谢!
更新:我想在服务而不是组件中执行此操作。
【问题讨论】:
在 Angular 中,您可以订阅路由器事件:
您想要的是NavigationStart 事件。
这是一个很好的代码示例,作为this StackOverflow question 上关于如何正确使用它的答案。
import { Router, ActivatedRoute, NavigationStart } from '@angular/router';
export class AppComponent {
constructor(public _router: Router, private _activeRoute: ActivatedRoute, private _location: Location) {
this.router = _router;
this.router.events
.filter(e => e instanceof NavigationStart)
.pairwise()
.subscribe((e) => { alert(e); });
}
}
【讨论】: