Angular 2.0,如何检测子组件上的路线更改 [英] Angular 2.0, how to detect route change on child component
问题描述
如何检测子组件上的路线更改? 这是我尝试过的方法,但是我只看到应用程序组件跟踪路线更改. 我希望能够检测到网址何时发生变化,例如在MetaDetailView组件中将#/meta/a/b/c更改为#/meta/a/b/c/d.
How can I detect a route change on a child component?. This is what I have tried, but I only see the app component trace the route change. I want to be able to detect when the url change from e.g. #/meta/a/b/c to #/meta/a/b/c/d in the MetaDetailView component.
@RouteConfig([
{ path: '/', name: 'Home', redirectTo: ['Meta']},
{ path: '/meta/...', name: 'Meta', component: MetaMainComponent, useAsDefault: true},
...other routes...,
])
export class AppComponent {
constructor(private _router: Router) {
_router.subscribe( (url) => console.log("app.url = " + url));
}
}
@RouteConfig([
{ path: '/*other', name: 'Detail', component: MetaDetailViewComponent, useAsDefault: true},
])
export class MetaMainComponent {
constructor(private _router: Router) {
_router.subscribe( (url) => console.log("metamain.url = " + url));
console.log("MetaMainComponent")
}
}
export class MetaDetailViewComponent {
constructor(private _router: Router) {
_router.subscribe( (url) => console.log("metadetail.url = " + url));
console.log("MetaDetailViewComponent")
}
}
谢谢 杰斯珀
推荐答案
创建一个预订router
的全局服务,并将该服务注入到您想知道的有关路由更改的任何位置.该服务可以通过Observable
本身公开更改,因此感兴趣的组件也可以订阅以自动获得通知.
Create a global service that subscribes to router
and inject the service wherever you want to know about route changes. The service can expose changes by an Observable
itself so interested components also can subscribe to get notified automatically.
这篇关于Angular 2.0,如何检测子组件上的路线更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!