如何在 Angular 2 中将 Route 数据获取到 App Component

How to get Route data into App Component in Angular 2

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

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

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

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,但每次重定向后都没有更新。

无论如何,我可以在哪里配置页面名称并在全局中获取它app.component.ts

尝试 filter 循环你的事件而不是 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

如果您使用 Router 对象进行静态路由,如下所示:

{
  path: '',
  pathMatch: 'full',
  component: NameComponent,
  data: { variableName: 'variableValue' }
},

在 ngOnInit() 上,您可以使用 ActivatedRoute 对象来恢复您从路由器定义传递的数据:

ngOnInit() {
  this.localVariable = this.route.snapshot.data['variableName'];
}

Obs:我正在使用 Angular 5!

对于Angular 5+

此服务检索当前路线上的数据:(在我的例子中是“title”)

import { Injectable } from "@angular/core";
import { Router, ActivatedRouteSnapshot } from "@angular/router";

@Injectable()
export class AppRoutingService {

  constructor(private router: Router) { }

  public getRouteTitle(): string {
    return this.getRouteData("title");
  }

  private getRouteData(data: string): any {
    const root = this.router.routerState.snapshot.root;
    return this.lastChild(root).data[0][data];
  }

  private lastChild(route: ActivatedRouteSnapshot): ActivatedRouteSnapshot {
    if (route.firstChild) {
      return this.lastChild(route.firstChild);
    } else {
      return route;
    }
  }
}

组件逻辑:

import { Component, OnInit, OnDestroy } from "@angular/core";
import { Router, NavigationEnd } from "@angular/router";

// SERVICES
import { AppRoutingService } from "../../shared/services/app-routing.service";

@Component()
export class NavSubmenuComponent implements OnInit, OnDestroy {
  title: string = "";
  routerEvents: any;

  constructor(private router: Router, private appRoutingService: AppRoutingService ) { }

  ngOnInit() {
    this.title = this.appRoutingService.getRouteTitle();

    this.routerEvents = this.router.events
      .filter(event => event instanceof NavigationEnd)
      .subscribe(() => {
        this.title = this.appRoutingService.getRouteTitle();
      });
  }

  ngOnDestroy() {
    this.routerEvents.unsubscribe();
  }
}

如果您愿意等到 ngAfterViewInit 事件,您可以 link 使用 viewchild 到路由器出口。

  @ViewChild('router')
  private routerOutlet: RouterOutlet;

  ngAfterViewInit() {
    this.routerOutlet.activateEvents
      .pipe(
        map(() => this.routerOutlet
          .activatedRouteData
        )
      )
    .subscribe((data) => {
        // Code 
    });
  }

<router-outlet #router="outlet"></router-outlet>

此代码由 Todd Motto(Google 开发专家)编写,用于访问 parent 组件或应用程序组件中的路由数据。像 gem.

一样工作
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router'
import { filter, map, mergeMap } from 'rxjs/operators'

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

ngOnInit() {
  this.router.events.pipe(
    filter(event => event instanceof NavigationEnd),
    map(() => this.route),
    map(route => {
      while (route.firstChild) route = route.firstChild
      return route
    }),
    filter(route => route.outlet === 'primary'),
    mergeMap(route => route.data)
  ).subscribe(data =>
    console.log('data', data)
  )
}

参见:https://ultimatecourses.com/blog/dynamic-page-titles-angular-2-router-events

在他的示例中,他使用路由数据在应用程序组件中设置页面标题。

为什么在 parent 中访问路由数据如此复杂我永远不会知道!

在我的例子中,这项工作适用于 angular 8:

onActivate(outlet) in <router-outlet> 每次激活路由时都会自动调用

在html

<router-outlet (activate)='onActivate(outlet)' #outlet="outlet"></router-outlet>

在组件中

onActivate(outlet: RouterOutlet) {
    outlet.activatedRoute.data.pipe(map(data => console.log('Router data', data))).toPromise().then();
  }

别忘了导入

import {RouterOutlet} from '@angular/router';
import {map} from 'rxjs/operators';

根据Angular文档,您可以轻松地使用它。

测试于 Angular 11.

https://angular.io/api/router/ActivatedRouteSnapshot#description

@Component({templateUrl:'./my-component.html'})
class MyComponent {
  constructor(route: ActivatedRoute) {
    const id: string = route.snapshot.params.id;
    const url: string = route.snapshot.url.join('');
    const user = route.snapshot.data.user;
  }
}

路线如:

{
  path: 'edit/:id',
  component: MyComponent,
  data: {
    user: 1,
    otherData: 'as string'
  }
}