【问题标题】:$locationChangeStart equivalent in Angular 4Angular 4 中的 $locationChangeStart 等价物
【发布时间】:2018-03-12 21:41:01
【问题描述】:

Angular 4 中的 $locationChangeStart 等价物是什么?我正在寻找一个处理程序来跟踪 url 的变化。我读到有一个location service,但我不确定我是否需要使用它或在这里寻找一些东西https://angular.io/guide/router.. 任何指针都会很有帮助。谢谢!

更新:我想在服务而不是组件中执行此操作。

【问题讨论】:

    标签: angular angular4-router


    【解决方案1】:

    在 Angular 中,您可以订阅路由器事件:

    您想要的是NavigationStart 事件。

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

    【讨论】:

    • 我可以在服务中使用它吗?
    • 是的,您可以在服务中使用它。但是,它已经作为公开可观察对象的服务提供,因此如果您打算提供“包装器”服务,这样做可能有点多余。
    猜你喜欢
    • 1970-01-01
    • 2016-04-19
    • 2013-09-16
    • 1970-01-01
    • 2013-03-02
    • 2021-09-11
    • 2019-04-10
    • 1970-01-01
    相关资源
    最近更新 更多