Angular 2.0, how to detect route change on child component

醉酒当歌 提交于 2019-12-05 21:12:10

问题


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")
    }
}

Thanks Jesper


回答1:


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.




回答2:


RC3+ solution:

constructor(private router: Router) {
  this.router.events.subscribe(event => {
    if (event.constructor.name === 'NavigationStart') {
      console.log(event.url);
    }
  });
}



回答3:


You have root access from any child router:

_router.root.subscribe(route => console.log('route', route));


来源:https://stackoverflow.com/questions/36157326/angular-2-0-how-to-detect-route-change-on-child-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!