Angular ActivatedRoute 数据返回一个空对象 [英] Angular ActivatedRoute data returns an empty object

查看:24
本文介绍了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.

如何解决这个问题?

推荐答案

问题是我试图从 外部 .所以看起来这是预期的行为.

不过,我仍然认为我下面的回答对任何试图完成同样事情的人都有用.

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).

这篇关于Angular ActivatedRoute 数据返回一个空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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