0

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.

2
  • Can you make a working sample on stackblitz.com? Commented Jul 25, 2021 at 6:58
  • 2
    You should return something from getOngoingClasses... Commented Jul 25, 2021 at 7:42

2 Answers 2

2

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));
}
Sign up to request clarification or add additional context in comments.

Comments

1

add return in end of map block . like this :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.