Angular2观察路线变化

时间:2015-12-23 22:40:33

标签: 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;
    }
}

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

6 个答案:

答案 0 :(得分:19)

如果您正在使用

"@angular/router": "3.0.0-alpha.7", 
"@angular/router-deprecated": "2.0.0-rc.2",

然后

this.router.events.subscribe((event) => {
      console.log('route changed');
});

答案 1 :(得分:19)

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

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

每次路线改变时,events Observable都会有信息。 点击here获取文档

答案 2 :(得分:17)

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

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

答案 3 :(得分:3)

事件是可观察的,因此您可以订阅它,我已成功在angular5

中尝试过
this.router.events.subscribe((event) => {
console.log(event);
 if(event['url'] && event['url'] == '/') {
    console.log('Home page');
    //any other functionality you can do here
 }
});

答案 4 :(得分:0)

如果你想在路由改变时捕获事件,并初始化一些代码,比如jQuery,那么使用OnActive hook。 例如:

import {Component} from 'angular2/core';
import {OnActivate,ComponentInstruction} from "angular2/router";
declare var $:any;
declare var Foundation:any;
@Component({
templateUrl :'/app/templates/home.html'
})
export class HomeComponent implements OnActivate{

  routerOnActivate(next: ComponentInstruction, prev: ComponentInstruction)
  {

    new Foundation.Orbit($("#es-slide-show"), {});
    return true;
  }
}

答案 5 :(得分:0)

这是最好的方法:

import { NavigationEnd, Router, RouterEvent } from '@angular/router'

constructor(private router: Router) {}

ngOnInit(): void {
  this.router.events.pipe(
    filter((evt: RouterEvent) => evt instanceof NavigationEnd)
  ).subscribe((evt: RouterEvent) => {
    // with the above filter, both the following will always log the same url
    console.log(evt.url)
    console.log(this.router.url)
  })
}