Get loaded component in parent resolver

395 Views Asked by At

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

1

There are 1 best solutions below

1
Ricardo Machado On

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")    
          }
        }
      })
    })    
  }
}