angularroutesresolver

How to use a resolver with angular routing


I have a resolver service that retrieves data from the db in transition, I receive the data in the service but not in the called component - it's undefine in the onInit

export class WorkShopResolverService implements Resolve<WorkShop | null>{

  constructor(private workShopService: WorkShopService) { }

  resolve(route: ActivatedRouteSnapshot,
          state: RouterStateSnapshot): Observable<WorkShop | null>{

    const workShopUuid = route.paramMap.get("workShopUuid");
    console.log("workShopUuid",workShopUuid);
    return this.workShopService.findWorkShopByUuid(Number(workShopUuid?.toString()));

  }
}

the component where I want to retrieve the information:

export class CreateWorkshopComponent implements OnInit, OnDestroy{
workShop!: WorkShop | null; ...}

app-routing:

{ path: 'createWorkShop/:workShopUuid', component: CreateWorkshopComponent, resolve:{ workShop: WorkShopResolverService } },


Solution

  • In your component you need to access your data from ActivatedRoute data.

      ...
      constructor(
        ...
        private route: ActivatedRoute
      ) {}
    
      ngOnInit(): void {
        const workShopData = this.route.snapshot.data.workShop;
      }