Angular 解析器 returns 未定义

Angular Resolver returns undefined

我是 angular 的新手,我正在尝试在我的 angular 中实施解决方案,其中我的需要是组件应该仅在数据可用时加载。但问题是解析代码在我可以在组件中捕获它之前执行,并且组件中返回的数据给出未定义的值。

解析代码:

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

组件代码:

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

路线代码:

    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' },
            ],
        },
    ];

请帮我解决这个问题。

您没有 return 从 getOngoingClasses 获取任何内容,这就是您的解析器 return 未定义的原因。您应该 return 一个可观察对象,而不是订阅某些东西:

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

在地图块的末尾添加 return。像这样:

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