0

I am unable to access parent object form activatedRoute in angular service, but it working fine in component. Is here any way to getting the same parent object in service.

import {ActivatedRoute} from '@angular/router'

constructor(private activatedRoute: ActivatedRoute) {}

In component:

 onEdit = ({ studentId }) => {
    console.log('parent ', this.activatedRoute.parent)
    // getting parent object
  }

In Service

onEdit = ({ studentId }) => {
        console.log('parent ', this.activatedRoute.parent)
        // getting null
      }
  • 1
    This is by design. ActivatedRoute provided information about routed components. A service is not a routed component. – MikeOne Aug 09 '20 at 19:54

1 Answers1

1

As MikeOne mentioned, it does not work by design. A service does not know about the activated route. Only the components routed to gets the ActivatedRoute segment passed.

You can however subscribe to route events in your service:

this.router.events
      .filter(event => event instanceof NavigationEnd)
      .map(() => this.activatedRoute)
      .map(route => {
        while (route.firstChild) route = route.firstChild;
        return route;
      })
      .filter(route => route.outlet === 'primary')
      .mergeMap(route => route.data)
      .subscribe((data) => ...);

Example is taken from https://github.com/angular/angular/issues/15004

Read this for more detailed explanation and alternate methods

p0d4r14n
  • 681
  • 5
  • 15