Angular2观察路线变化

Arū*_*kas 25 typescript angular

@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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Hin*_*ich 24

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

this.router.events.subscribe((event) => {
    if(event.url) {
        console.log(event.url);
    }
});
Run Code Online (Sandbox Code Playgroud)

每次路线改变时,eventsObservable都会有信息.点击此处查看文档.

  • 属性url在类型事件上不存在. (6认同)
  • 这样做了!请注意路由器元素是路由器的一个实例:你应该从'@ angular/router'执行```import {Router};```和```constructor(private router:Router){}```. (4认同)

Dim*_*dha 20

如果你正在使用

"@angular/router": "3.0.0-alpha.7", 
"@angular/router-deprecated": "2.0.0-rc.2",
Run Code Online (Sandbox Code Playgroud)

然后

this.router.events.subscribe((event) => {
      console.log('route changed');
});
Run Code Online (Sandbox Code Playgroud)


小智 17

这是我在我的应用程序中使用的内容.您可以订阅Route实例以跟踪更改.

class MyClass {
  constructor(private router: Router) {
    router.subscribe((val) => /*detect changes*/)
  }
}
Run Code Online (Sandbox Code Playgroud)

  • @ulydev请你提供plnkr或工作代码这个routerChange检测我无法得到你如何使用你的代码. (2认同)