Pass static data to parent resolver from child route

559 Views Asked by At

I have a resolver which should run on every route change and should work with data passed to it. That data is different for every route.

enum PageId {
  FirstPage = 'firstPage',
  SecondPage = 'secondPage'
};

const routes: Routes = [
  {
    path: '',
    resolve: {
      content: ContentResolver
    },
    runGuardsAndResolvers: 'always',
    children: [
      {
        path: 'first',
        component: FirstStepComponent,
        data: { contentId: PageId.FirstPage }
      },
      {
        path: 'second',
        component: SecondStepComponent,
        data: { contentId: PageId.SecondPage }
      }
    ]
  }
];

Unfortunately the resolver doesn't see the data specified in child routes. (ActivatedRouteSnapshot -> data object)

The desired behavior could be achieved by copy-pasting the resolver to every child route, but I would like to have the mentioned generic solution with the parent resolver if possible.

Most probably the URL could be used to replace the need of static data in the resolver, but in that case I would have to create a mapper function between URL and enum in the resolver, what I would like to avoid.

2

There are 2 best solutions below

0
gr4viton On

I think there is a valid solution.

The pages can have the same static property.

static pageId = PageId.SecondPage;

Static property can be accessed in the resolver on the ‘component’ property of ‘ActivatedRouteSnapshot’.

5
AudioBubble On

Your resolver is on the parent component of the routes you want to check.

So you have to check the children.

Assuming you have a single child route (no named outlets) :

this.route.firstChild.data;

Otherwise, use children in place of firstChild and find the corresponding child in it.