我试图在显示详细信息组件之前从路由中获取数据并将数据加载到我的状态,因此我创建了一个解析器。我知道我的get请求正在工作,但是好像在组件加载后api调用完成了。
@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);
}
}
这些是我的路线,其中我明确将解析器应用于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 }
]
}
];
最后是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});
}
}
要解释我解析器中代码的目的是什么,请从我的API分派用于从id提取workOrder的操作,并将其存储在状态中(此方法有效),一旦完成,仅在完成之后,返回我存储在状态中的workOrder的可观察值,并加载WorkOrderDetailComponent。
错误:视图在第一次加载路由时无法读取workOrder的null值,但是随后发生的是,如果我离开并返回该页面,则workOrder不再为null。所以我的猜测是,由于某种原因,解析器在加载组件之前没有做到这一点。我想要的是解析程序返回Observable <{WorkOrder]>,以便可以在视图中以异步方式加载它。
此外,这可能是我没有正确使用rxjs运算符的问题,我很难把握可观察对象的工作方式以及这些运算符如何链接。如果是这样,请告诉我什么地方错了,为什么。
谢谢!
答案 0 :(得分:1)
您应该等到选择器返回一个值
this.store.pipe(
select(state => state.workOrder.workOrderDetails),
filter(details => !!details),
take(1)
);
请注意,我还在商店上使用select
运算符,而不是select
方法。这是因为不建议使用商店中的select
方法,以后会删除它。