Chiien
Chiien

Reputation: 341

How get current route data in angular 5

In my situation now, I put data object in my lazy load component, and I want to get data content and show in the html. But I couldn't do it. Here is the script:

const routes: Routes = [
    {
        path: '',
        component: CancellationComponent,
        data: {
            animation: 'cancellation',
            title: 'Cancelamento de contratos'
        },
        resolve: {
            data: CancellationResolveService
        }
    }
];

The component is loaded by Lazy Load. What I want is, when I access directly in #/cancellation, I want to get the data content, what is the best way? Any idea? Thanks a lot!

Upvotes: 3

Views: 18566

Answers (5)

cr7 aj7
cr7 aj7

Reputation: 99

Try this code

this.router.getCurrentNavigation()

this.router.getCurrentNavigation().extras.state will have the state params

Upvotes: 0

user1
user1

Reputation: 1135

Another way to get the current route data as an rxjs stream would be:

constructor(router: Router) {
    const routeData$ = router.events.pipe(
        filter(e => e instanceof ActivationEnd), 
        throttleTime(0),
        map((e: ActivationEnd) => e.snapshot.data)
    );
  }
  1. Get the router service using the DI.

  2. Pipe the router events and filter the activation end events (we can get the route snapshot there and get the data property)

  3. Throttle the events for the current stack. If we have nested routes the events will be fired for the bottom most route to the top and we only need the first (which is the current one) so throttle will get this first ActivationEnd event and will push it through the stream and filter out the rest for the current navigation.

  4. Then we get the data from the current snapshot

  5. And inside the subscription (where ever that is) you will have the data for the current route.

Also if we want to merge all the data from the different ActivationEnd events for the different routes into one object we could also do:

constructor(router: Router) {
  router.events.pipe(
    filter(e => e instanceof ActivationEnd),
    buffer(router.events.pipe(filter(e => e instanceof NavigationEnd), debounceTime(0))),
    map((events: ActivationEnd[]) => events.reduce((acc, curr) => ({ ...acc, ...curr.snapshot.data }), {}))
  );
}
  1. Filter out for the ActivationEnd events (we have the route snapshots there so we can get the data for the individual routes from them)

  2. buffer them until we've gotten all the NavigationEnd events for the current stack

  3. reduce over all the buffered events and collect the data inside one object (collisions are not handled)

Or use the first solution with paramsInheritanceStrategy

Upvotes: 1

DeborahK
DeborahK

Reputation: 60518

You can access the route's data property from the snapshot like this:

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

@Component({
    templateUrl: './app/home/welcome.component.html'
})
export class WelcomeComponent implements OnInit {
    public pageTitle: string;

    constructor( private route: ActivatedRoute) {
    } 

    ngOnInit(): void {
     this.pageTitle = this.route.snapshot.data['title'];
  }

}

This requires injecting the ActivatedRoute, then accessing the route's snapshot. You can use the snapshot instead of subscribing since the data is static.

Hope this helps.

Upvotes: 13

Wandrille
Wandrille

Reputation: 6811

Depending where you want to use it, But if it's elevated, you can try:

constructor(private router: Router,
            private activatedRoute: ActivatedRoute)

You will detect every change of route and get the data in the route.

router.events.pipe(
      filter(event => event instanceof NavigationEnd), // Only get the event of NavigationEnd
      map(() => activatedRoute), // Listen to activateRoute
      map(route => {
        while (route.firstChild) {
          route = route.firstChild;
        }
        return route;
      }),
      filter(route => route.outlet === 'primary'),
      mergeMap(route => route.data)  // get the data
    )

Upvotes: 7

Timothy
Timothy

Reputation: 3593

ActivatedRoute has data property

Upvotes: 0

Related Questions