简体   繁体   中英

Angular 6: Skip parent route resolver in child route?

I'm trying to add routes to my app, and I have a parent route with parentResolver and a child route with Child Resolver. When I access the '/parent', the parent resolver kicks in perfectly.

But the problem is, when I access '/parent/child', the parent resolver kicks in again before the child resolver can kick in. I don't want to run the parent resolver when I'm navigating to a child page.

So is there a way to skip the parent resolver when child route is called. Here's my route config

{
    path: 'parent',
    component: ParentComponent,
    resolve: {parentData: ParentResolver},
    runGuardsAndResolvers: 'paramsOrQueryParamsChange',
    children: [
      {
        path: 'child',
        component: ChildComponent,
        resolve: {childData: ChildResolver},
        runGuardsAndResolvers: 'paramsOrQueryParamsChange'
      }
    ]
  }

Try the following:

{
    path: 'parent',
    children: [
               {  path : '',
                  pathMatch : 'full',
                  component: ParentComponent,
                  resolve: {parentData: ParentResolver},
                  runGuardsAndResolvers: 'paramsOrQueryParamsChange',
               },
               {  path: 'child',
                  component: ChildComponent,
                  resolve: {childData: ChildResolver},
                  runGuardsAndResolvers: 'paramsOrQueryParamsChange'
               }
             ]
}
  1. Check in parent resolver what is target path. (or if ActivatedRouteSnapshot has children)

     resolve(route: ActivatedRouteSnapshot) { if (route.children.length) { // target is some child } else { // target is parent }

    }

  2. Create standalone path: 'parent/child'

You can create what I call a ResolverGuard, which is a Guard that acts as a Resolver.

{
path: 'parent',
component: ParentComponent,
resolve: [ParentResolver], // simply return an Observable<boolean>
runGuardsAndResolvers: 'paramsOrQueryParamsChange',
children: [
  {
    path: 'child',
    component: ChildComponent,
    canActivate: [ChildResolverGuard],
    runGuardsAndResolvers: 'paramsOrQueryParamsChange'
  }
]

}

However, this will simply run the child guard before the parent Resolver. The resolver will run regardless, but you can add logic in the ParentResolver to skip it if the child Guard ran.

Checkout https://github.com/angular/angular/issues/20805#issuecomment-350106463

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM