0

I'm trying to access the component's name in parent resolver, but it is always undefined. It might be a limitation of the angular router, a not implemented feature, or an intentional behaviour, because at that point the component is not identified.

Imagine having a parent resolver. This route has child routes.

const routes: Routes = [
  {
    path: '',
    resolve: {
      content: ContentResolver,
    },
    runGuardsAndResolvers: 'always',
    children: [
      {
        path: 'a',
        component: AComponent,
        data: {
          contentId: 'AContentId',
        },
      },
      ...
    ]
  }
];
export class ContentResolver implements Resolve<boolean> {
  constructor() {}

  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> {
    console.log(route.component);
    return of(true);
  }
}

When I navigate to route a I expect to see AComponent as value of route.component. It is undefined.

Stackblitz

gr4viton
  • 1,434
  • 1
  • 8
  • 21
  • Have console.log(route)? what is result? – Vega Jul 10 '22 at 14:59
  • Route is an object. This object has a property called component, which is undefined. If you define a resolver next to the route (so not a parent resolver), then the component property is set correctly. – gr4viton Jul 10 '22 at 15:16
  • What is in children? https://angular.io/api/router/ActivatedRouteSnapshot – Vega Jul 10 '22 at 15:16
  • @Vega I updated the OP with a stackblitz link. – gr4viton Jul 10 '22 at 15:19
  • state.root.component always has AppComponent as value. The point is to get the activated child route's component. E.g. you click navigate to 'b', so the component should be BComponent – gr4viton Jul 10 '22 at 18:10

1 Answers1

0

Like you said, this is surely a childrens problem. You can loop until you dont find your data. Something like this:

@Injectable({ providedIn: 'root'})
export class HeroResolver implements Resolve<HeroService> {
  constructor(private service: HeroService) {}

  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot,
  ): Observable<any> | Promise<any>  {
    return new Promise((resolve, reject) => {
      route.children.forEach((children) => {
        if(children.data != {}){
          if(children.data.contentId){ 
            resolve("Something with your data")    
          }
        }
      })
    })    
  }
}
Ricardo Machado
  • 787
  • 1
  • 8
  • 16
  • 1
    It is not enough, because there could be nested routes, where we want to do something with the activated route's data and also with its parent's data. I'm gonna update the OP with a stackblitz. – gr4viton Jul 10 '22 at 15:17