Typescript Angular2观察路线变化

Typescript Angular2观察路线变化,typescript,angular,Typescript,Angular,我需要更改每次路线更改的变量值,如何在Angular 2.x中观察此事件?以下是我在应用程序中使用的内容。您可以订阅路由实例以跟踪更改 @RouteConfig([ {path: '/about', name: 'About', component: About, useAsDefault: true}, {path: '/test', name: 'Test', component: Test} ]) export class MyApp { router: Rout

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

以下是我在应用程序中使用的内容。您可以订阅路由实例以跟踪更改

@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;
    }
}

如果您希望在路由更改时捕获事件,并初始化一些代码(如jQuery),则使用
OnActive
hook。 例如:

class MyClass {
  constructor(private router: Router) {
    router.subscribe((val) => /*detect changes*/)
  }
}
如果您正在使用

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;
  }
}
然后


在Angular的最终版本(例如Angular 2/4)中,您可以执行此操作

this.router.events.subscribe((event) => {
      console.log('route changed');
});
每次路线更改时,
事件
可观察到的信息都会显示。
点击查看文档

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

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

抱歉,在您更改Angular2的答案之前,您否决了此选项,这是正确的。谢谢!工作完美。@ulydev请您为此路由器更改检测提供plnkr或工作代码,我不知道如何使用您的代码。router.subscribe不会与angular beta一起启动。2有什么想法吗?试试这个。router.changes.subscribe新路由器(=>RC.3)看看这是当前版本的正确答案。这很难找到+1+1您的答案对Angular2的当前版本有效
this.router.subscribe()
不再工作。相反,您需要订阅Dimpu声明的
事件
!这就成功了!请注意,router元素是router的一个实例:您应该
从'@angular/router'导入{router}
构造函数(专用路由器:路由器){}
。类型事件上不存在属性url。您能回答此问题吗?Sixttwo49843Net现在Angular中有多个事件类型,因此您需要首先检查事件类型。然后您可以使用每个的特定属性。例如,
if(event instanceof NavigationEnd){event.url…;}
有关更多类型,请参阅此处的文档:angular 6上的有效答案
this.router.events.subscribe((event) => {
    if(event.url) {
        console.log(event.url);
    }
});
this.router.events.subscribe((event) => {
console.log(event);
 if(event['url'] && event['url'] == '/') {
    console.log('Home page');
    //any other functionality you can do here
 }
});