我用一些数据注册了一条路由:

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

我正在try 使用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是一个空的物体.

如何解决这个问题?

推荐答案

Edit: 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.

然而,我仍然认为我下面的答案对任何试图完成同样任务的人都是有用的.


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

Typescript相关问答推荐

如何根据数据类型动态注入组件?

Typescript对每个属性具有约束的通用类型

TypeScript泛型参数抛出错误—?&#"' 39;预期"

将值添加到具有不同类型的对象的元素

与字符串文字模板的结果类型匹配的打字脚本

TypeScrip:逐个 case Select 退出noUncheck kedIndexedAccess

如何使用类型谓词将类型限制为不可赋值的类型?

是否可以强制静态方法将同一类型的对象返回其自己的类?

如何将类似数组的对象(字符串::匹配结果)转换为类型脚本中的数组?

TS2739将接口类型变量赋值给具体变量

如何键入并类型的函数&S各属性

为什么TypeScrip假定{...省略类型,缺少类型,...选取类型,添加&>}为省略类型,缺少类型?

为什么我会得到一个;并不是所有的代码路径都返回一个值0;switch 中的所有情况何时返回或抛出?(来自vsCode/TypeScript)

两个接口的TypeScript并集,其中一个是可选的

如何使用 Angular 确定给定值是否与应用程序中特定单选按钮的值匹配?

如何向我的自定义样式组件声明 custom.d.ts ?

对象只能使用 Typescript 中另一个对象的键

Select 器数组到映射器的Typescript 泛型

如何在 ngFor 循环中以Angular 正确动态渲染组件

req.files = 未定义(Multer、Express、Typescript)