![](/img/trans.png)
[英]Angular2 resolver returns undefined when the data service console logs the data fine
[英]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' },
],
},
];
請幫我解決這個問題。
您沒有從getOngoingClasses
返回任何內容,這就是您的解析器返回 undefined 的原因。 與其訂閱某些東西,不如返回一個可觀察的對象:
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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.