如何获得角度2的当前路线自定义数据?

Rit*_*tan 25 angular2-routing angular

我设置的路线如下

const appRoutes: Routes = [
  {
    path: 'login',
    component: LoginComponent,
    data: {
      title: 'Login TTX'
    }
  },
  {
    path: 'list',
    component: ListingComponent,
    data: {
      title: ' TTX Home Page',
      module:'list'
    }
  },
  {
    path: '',
    redirectTo: '/login',
    pathMatch: 'full'
  },
];
Run Code Online (Sandbox Code Playgroud)

现在,当我来'/list' 路线然后'listing.component.ts'我写下面的代码

export class ListingComponent {

  public constructor(private router:Router) {
      //here how i can get **data** of **list** routes

  }
}
Run Code Online (Sandbox Code Playgroud)

asm*_*mud 23

对于Angular 4+

如果您将以下代码放在父级或更高级别的组件中,AppComponent那么它将无法正常工作.它仅适用于您已为其定义路径自定义数据的子级或低级组件:

 public constructor(private route:ActivatedRoute, private router:Router) {
      console.log(route.snapshot.data['title']);
  }
Run Code Online (Sandbox Code Playgroud)

因此,如果要从父级或上级组件全局访问路由自定义数据以访问路由自定义数据中的更改,那么您将特别侦听路由器事件RoutesRecognizedNavigationEnd事件.我AppComponent要用两个事件来展示两个程序:

第一种方法:

   export class AppComponent implements OnInit, AfterViewInit {

    constructor(private activatedRoute: ActivatedRoute, private router: Router) { }

    ngOnInit() {
         this.router
        .events
        .filter(event => event instanceof NavigationEnd)
        .map(() => {
          let child = this.activatedRoute.firstChild;
          while (child) {
            if (child.firstChild) {
              child = child.firstChild;
            } else if (child.snapshot.data && child.snapshot.data['custom_data']) {
              return child.snapshot.data['custom_data'];
            } else {
              return null;
            }
          }
          return null;
        }).subscribe( (customData: any) => {
          console.log(customData);
       });
    }
 }
Run Code Online (Sandbox Code Playgroud)

第二种方法是使用:

this.router.events
.filter(event => event instanceof RoutesRecognized)
.map( (event: RoutesRecognized) => {
    return event.state.root.firstChild.data['custom_data'];
})
.subscribe(customData => {
    console.log(customData);
});
Run Code Online (Sandbox Code Playgroud)

注意:尽管最后一个较短且通常有效,但是,如果您有嵌套路线,则鼓励使用第一个.

  • 太好了,您的第一种方法很有帮助。谢谢!对于其他人:您必须导入“rxjs/add/operator/filter”和“rxjs/add/operator/map”才能使其工作 (2认同)

Gün*_*uer 18

  public constructor(private route:ActivatedRoute, private router:Router) {
      console.log(route.snapshot.data['title']);
  }
Run Code Online (Sandbox Code Playgroud)

  • 问题是这条路线不是最后的路线,它是一个嵌套的树.这真的取决于你把这件作品放在哪里,那么你只是在这里玩运气. (6认同)
  • 这不会总是给您正确的结果,因为这取决于您放置它的位置。 (2认同)

win*_*mao 7

在我测试了各种解决方案后,角度支持小组的答案实际上很好地解决了这个问题.

ActivatedRoute不携带数据,这里是检测页面变量的解决方案data: { page: 'login' }.

import { Router, RoutesRecognized } from '@angular/router';

export class AppComponent {
  page = '';
  constructor(private router: Router) {
    // listen to page variable from router events
    router.events.subscribe(event => {
      if (event instanceof RoutesRecognized) {
        let route = event.state.root.firstChild;
        this.page = 'page-' + route.data.page || '';
        console.log('Page', this.page);
      }
    });
  }
}
Run Code Online (Sandbox Code Playgroud)


izi*_*k f 6

它为无法导航的组件工作(如标题):

this.route.root.firstChild.snapshot.data['title']
Run Code Online (Sandbox Code Playgroud)

并编译示例:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router, NavigationEnd } from '@angular/router';


export class HeaderComponent implements OnInit {
  title: string;

  constructor(private route: ActivatedRoute, private router: Router ) { }

  ngOnInit() {
    this.router.events.subscribe(event => {
      if(event instanceof NavigationEnd) {
        this.title = this.route.root.firstChild.snapshot.data['title']
      }
    });
  }    
}
Run Code Online (Sandbox Code Playgroud)

cerdit到这个answare


Vic*_*ves 5

直到Angular 5.x为止,asmmahmud的Answer效果很好,this.router.events因为rxjs 6.x具有重大更改,因此6.X 无效。所以刚遇到一个更新:

import {filter} from 'rxjs/operators';
import {map, mergeMap} from 'rxjs/internal/operators';

router.events
          .pipe(filter(event => event instanceof NavigationEnd),
            map(() => {
              let route = activatedRoute.firstChild;
              let child = route;
              while (child) {
                if (child.firstChild) {
                  child = child.firstChild;
                  route = child;
                } else {
                  child = null;
                }
              }
              return route;
            }),
            mergeMap(route => route.data)
          )
          .subscribe(data => {
            console.log(data);
          });
Run Code Online (Sandbox Code Playgroud)