mindparse
mindparse

Reputation: 7225

Angular 6 - How to access route resolved data from non routed components

I am working with Angular 6 and have a non routed component that needs to access resolved data from a route I am navigating to.

Reading around I think I need to make use of router events to allow my component to know when a NavigationEnd event has occurred.

So far I have this in my ngOnInit():

this.router.events.pipe(
  filter(event => event instanceof NavigationEnd)
  ).subscribe((route: ActivatedRoute) => {
      console.log(route);
  });

But when I look at the output in my console I only get a few properties like so:

NavigationEnd {id: 2, url: "/trip-schedule", urlAfterRedirects: "/trip-schedule"}

I have also noticed, I only get this event fired when I navigate to a state using an element that is bound to a routerLink. if I call navigate() on the router instance itself, I don't see any output logged.

Is there a different way I should be approaching this?

Thanks

Upvotes: 2

Views: 3173

Answers (1)

Michal.S
Michal.S

Reputation: 531

Route data can be read from ActivatedRoute as:

    @Component({
      selector: 'app-root',
      template: `<router-outlet></router-outlet>`,
      styleUrls: ['./app.component.css'],
    })
    export class AppComponent   {

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

       this.router.events.pipe(
          filter(event => event instanceof NavigationEnd)
        ).subscribe((route: ActivatedRoute) => {
          console.log(route);
          console.log(this.route.snapshot.firstChild.data);
       });

    }

but with this solution you have to know how deep and where is your interesting ActivatedRoute using some accessors root,firstChild,children,parent etc... My example is simplified.

Upvotes: 3

Related Questions