3

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.

JM Gelilio
  • 3,482
  • 1
  • 11
  • 23
gr4viton
  • 1,434
  • 1
  • 8
  • 21

2 Answers2

1

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.

  • Unfortunately my real route structure contains 2-3 level nested routes, so simply accessing the data of firstChild is not a solution I'm looking for. – gr4viton Jun 24 '22 at 12:24
  • @gr4viton you can make a recursive loop checking for every parent then –  Jun 29 '22 at 11:31
  • You mean every child. The problem is that if I want to load the third component in the children array, and every component in the array contains contentId with different values, then I can't tell the resolver which contentId it supposed to use, because it should be the third. – gr4viton Jul 02 '22 at 21:05
  • No I meant every parent. You have to browse up in order to not check every element of your routes (that would be too much and useless). And it also answers your comment about not knowing the third element : evey child has only one parent, so you know every ID –  Jul 05 '22 at 12:36
  • Please could you show me what you have in mind by updating this stackblitz: https://stackblitz.com/edit/angular-ivy-dy4duk?file=src/app/content.resolver.ts – gr4viton Jul 10 '22 at 11:43
0

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’.

gr4viton
  • 1,434
  • 1
  • 8
  • 21