Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
955 views
in Technique[技术] by (71.8m points)

typescript - Angular ActivatedRoute data returns an empty object

I have a route registered with some data:

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

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 {}
    });
  }
}

but for some reasons data is an empty object.

How to solve this problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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


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;
      }
    });
  }
}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...