I'm currently facing an issue with fetching data from a route and loading it into my state before displaying my detail component. To tackle this, I've implemented a resolver. Although my get request seems to be functioning, it appears that the API call is happening post component load.
@Injectable()
export class WorkOrderDetailResolver implements Resolve<WorkOrder> {
constructor(
private store: Store<fromApp.AppState>
) { }
waitForWorkOrderDataToLoad(route, state) {
this.store.dispatch(new WorkOrderActions.FetchWorkOrderFromAPIByID(+route.params['id']));
return this.store.select(state => state.workOrder.workOrderDetails).pipe(take(1));
}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<WorkOrder> | Promise<WorkOrder> | WorkOrder {
return this.waitForWorkOrderDataToLoad(route, state);
}
}
Here are the routes where I've clearly integrated the resolver into the WorkOrderDetailsComponent
const workOrderRoutes: Routes = [
{
path: 'workorders',
component: WorkOrderComponent,
children: [
{ path: 'new', component: WorkOrderEditComponent },
{ path: 'list', component: WorkOrderListComponent },
{ path: ':id', component: WorkOrderDetailComponent, resolve: { workOrderDetails: WorkOrderDetailResolver } },
{ path: ':id/edit', component: WorkOrderEditComponent }
]
}
];
Lastly, here's the code for the WorkOrdersDetailComponent:
@Component({
selector: 'app-work-order-detail',
templateUrl: './work-order-detail.component.html',
styleUrls: ['./work-order-detail.component.css']
})
export class WorkOrderDetailComponent implements OnInit {
private id: number;
workOrder: WorkOrder;
workOrderState: Observable<{workOrders: WorkOrder[]}>;
constructor(private route: ActivatedRoute,
private router: Router,
) { }
ngOnInit() {
console.log(this.route.snapshot.data);
this.workOrder = this.route.snapshot.data.workOrderDetails;
}
onEditWorkOrder() {
this.router.navigate(['edit'], {relativeTo: this.route});
}
}
To clarify the objective of the resolver code: It dispatches an action to fetch a workOrder by id from the API, stores it in the state (which works), and only then returns an observable of the workOrder stored in the state to load the WorkOrderDetailComponent.
The issue arises where the view cannot read the value of null for the workOrder the first time the route loads. However, upon navigating away and back to the page, the workOrder is no longer null. It seems like the resolver might not be functioning before the component loads. My intention is for the resolver to return Observable<{WorkOrder]> so that I can asynchronously load it in the view.
This could potentially be due to my misuse of rxjs operators for observables. I'm struggling to understand how observables function and how these operators should be properly chained. If that's the case, I would appreciate any insights on what's incorrect and why.
Thank you!