Angular ActivatedRoute数据返回一个空对象

问题描述:

我有一条记录了一些数据的路线:

I have a route registered with some data:

const routes: Routes = 
[
    {path: 'my-route', data: { title: 'MyTitle' }, component: MyComponent},
];

,而我正尝试使用ActivatedRoute访问该路线的数据:

and I'm trying to access to the route's data using ActivatedRoute:

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

@Component({...})
export class MyComponent implements OnInit {
  private routeData;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.routeData = this.route.data.subscribe((data) => {
      console.log(data); // this is returning an empty object {}
    });
  }
}

但是由于某些原因,data是一个空对象.

but for some reasons data is an empty object.

如何解决这个问题?

问题是我试图从外部 <router-outlet>的组件访问ActivatedRoute.因此,这似乎是预期的行为.

但是我仍然认为,我的以下回答对尝试完成同一任务的任何人都有用.

the problem is that I was trying to access the ActivatedRoute from a Component which is outside the <router-outlet>. So it looks like that this is the intended behaviour.

However I still think that my answer below can be useful to anyone who is trying to accomplish the same thing.


我在GitHub上找到了一种变通方法(感谢 manklu ),该变通方法用于完成我需要的工作:


I found a workaround on GitHub (thanks manklu) that I used in order to accomplish what I needed:
import { Component, OnInit } from '@angular/core';
import { Router, RoutesRecognized } from '@angular/router';

@Component({...})
export class MyComponent implements OnInit {
  private routeData;

  constructor(private router: Router) { }

  ngOnInit() {
    this.router.events.subscribe((data) => {
      if (data instanceof RoutesRecognized) {
        this.routeData = data.state.root.firstChild.data;
      }
    });
  }
}

以这种方式this.routeData将保存我需要的路线数据(在我的情况下是页面title).

doing this way this.routeData will hold the route data that I needed (in my case the page title).