如何在Angular 2中将路径数据导入App组件 [英] How to get Route data into App Component in Angular 2

查看:96
本文介绍了如何在Angular 2中将路径数据导入App组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用路由模块中定义了一些路由数据,如下所示:

I have defined some route data in my app routing module like below:

    const appRoutes:Routes = [
  {path: '', component: LoginComponent, data:[{PageName:"Login Page"}]}]

我想全局获取数据,以便我可以在app.component.ts中使用appRoutes来获取与URL重定向相关的信息,如下所示:

I want to get the data globally so that I can use appRoutes in app.component.ts to get the URL redirection related information as below:

export class AppComponent {
  title = 'Welcome';
  constructor(public router: Router, public authenticationService: AuthenticationService) {
    this.router.events.subscribe(event => {
        console.log("Url",event.urlAfterRedirects);
        console.log("Page Name", router[PageName]); //Not working
      }

我尝试注入ActivatedRoute,但每次重定向后都没有更新。

I tried injecting ActivatedRoute but it's not getting updated after each redirection.

无论如何,我可以在哪里配置页面名称并将其输入全局 app.component.ts

Is there anyway, where I can configure page name and get it in global app.component.ts.

推荐答案

尝试过滤并循环您的活动,而不是订阅

Try to filter and loop your events instead of subscribe

constructor(router:Router, route:ActivatedRoute) {
    router.events
      .filter(e => e instanceof NavigationEnd)
      .forEach(e => {
        this.title = route.root.firstChild.snapshot.data['PageName'];
    });
}

请检查以下工作演示: https://plnkr.co/edit/rBToHRaukDlrSKcLGavh?p=info

Please check the following working demo: https://plnkr.co/edit/rBToHRaukDlrSKcLGavh?p=info

这篇关于如何在Angular 2中将路径数据导入App组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆