Ahmad
Ahmad

Reputation: 141

Angular Resolver returns undefined

I am new to angular and I am trying to implement the resolve in my angular wherein my need is that the component should load only when the data is available. But the issue is that the resolve code executes before I could catch it in the component and the returned data in the component gives undefined value.

Resolve Code:

    export class RouteResolver implements Resolve<any> {
    
      ongoingClasses: any;
      sortedDataClasses: any;
      
      constructor(
        public commonService: CommonService,
        private router: Router,
      ) { }
    
      resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
        return this.getOngoingClasses();
      }
    
      getOngoingClasses(): any {
        debugger;
        this.commonService.API_URL = `${environment.apiUrl}/admin/dashboardOngoingClasses?limit=10&offset=0&searchInput=`;
        this.commonService.getList().subscribe(
          response => {
            this.ongoingClasses = response?.data;
          }
        );
      }
    
    }

Component Code:

    ngOnInit(): void {
        debugger
        this.activateRoute.data.subscribe((results: { results: any }) => {
          console.log(results.results);
        });
      }

Route Code:

    const routes: Routes = [
        {
            path: '',
            component: HomeComponent,
            children: [
                {
                    path: 'dashboard',
                    component: DashboardComponent,
                    canActivate: [AuthGuard],
                    resolve: {
                        results: RouteResolver
                    }
                },
    
                { path: '', redirectTo: 'home', pathMatch: 'full' },
                { path: '**', redirectTo: 'home', pathMatch: 'full' },
            ],
        },
    ];

Please help me in resolving this.

Upvotes: 0

Views: 1116

Answers (2)

Reza Rouzbahani
Reza Rouzbahani

Reputation: 63

add return in end of map block . like this :

return this.commonService.getList().pipe(map(response => return response?.data));

Upvotes: 1

Aviad P.
Aviad P.

Reputation: 32629

You are not returning anything from getOngoingClasses that's why your resolver returns undefined. Instead of subscribing to something, you should return an observable:

getOngoingClasses(): any {
  debugger;
  this.commonService.API_URL = `${environment.apiUrl}/admin/dashboardOngoingClasses?limit=10&offset=0&searchInput=`;
  return this.commonService.getList().pipe(map(response => response?.data));
}

Upvotes: 2

Related Questions