Angular2监视路线更改 [英] Angular2 watch for route change

查看:81
本文介绍了Angular2监视路线更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@RouteConfig([
    {path: '/about', name: 'About', component: About, useAsDefault: true},
    {path: '/test', name: 'Test', component: Test}
])

export class MyApp {
    router: Router;
    location: Location;
    isCollapsed: boolean = true;

    // ON ROUTE CHANGE {
        this.isCollapsed = true;
    // }

    constructor(router: Router, location: Location) {
        this.router = router;
        this.location = location;
    }
}

我需要在每次路线更改时更改变量值,如何在Angular 2.x中监视此事件?

I need change variable value on every route change, how to watch for this event in Angular 2.x?

推荐答案

在Angular的最终版本(例如Angular 2/4)中,您可以这样做

In the final version of Angular (e.g. Angular 2/4), you can do this

this.router.events.subscribe((event) => {
    if(event.url) {
        console.log(event.url);
    }
});

每当路线更改时,events可观察到的信息. 点击此处 文档.

Every time the route changes, events Observable has the info. Click here for docs.

这篇关于Angular2监视路线更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆