【发布时间】:2020-05-04 04:57:35
【问题描述】:
从ngrx+ api http请求请求数据时我想做一个加载
我有一个包含加载布尔值的状态,另一个包含原始数据。
当数据到达时,我将 loading 设置为 false。
问题viewChild 找不到参考,因为数据在加载之前到达设置为假。
我得到错误
ERROR TypeError: Cannot read property 'nativeElement' of undefined
这是模板
<div *ngIf="isLoading; else kpi"><mat-spinner></mat-spinner></div>
<ng-template #kpi>
<div class="chartWrapper">
<div class="scrollArea">
<div class="chartAreaWrapper">
<canvas #lineChart id="lineChart" width="1200" height="400"></canvas>
</div>
</div>
<canvas #stickyAxis id="chartAxis" height="400" width="0"></canvas>
</div>
</ng-template>
在组件中
export class BranchKpisComponent implements OnChanges, OnInit, OnDestroy {
@ViewChild('lineChart', { static: true }) private chartRef;
我正在使用 ngrx 商店
我有选择器
selectLoadings$ = this.store.pipe(select(selectLoadings));
selectedDataByBranch$ = this.store.pipe(
select(selectBranchDirections, {
branchId: this.branchId,
location: 'directionsByBranch',
dir: 0
})
在ngOnchange()里面我订阅了loading和data observable(分开)
this.selectLoadings$.subscribe(
loading => (this.isLoading = loading.directionsByBranch[this.branchId])
);
this.selectedDataByBranch$
.pipe(filter(data => Object.keys(data).length > 0))
.subscribe(selectedDataByBranch => {
this.trainsDatasets = this.getDatasets(selectedDataByBranch);
this.context = this.chartRef.nativeElement; ### Error undefined chartRef
当我获取数据时在减速器内部我将加载设置为 false
case ESchedulesActions.GetAllSchedulesByDirectionSuccess: {
return {
...state,
directionsByBranch: {
...state.directionsByBranch,
[action.payload[1]]: action.payload[0]
},
loadings: {
...state.loadings,
directionsByBranch: {
...state.loadings.directionsByBranch,
[action.payload[1]]: false
}
}
};
}
【问题讨论】:
-
它本身说 chartRef 是未定义的。你有没有添加任何参考??
-
是的,我已经更新了答案
-
问题在于将 loading 更改为 false 只会在当前事件处理阶段完成后更新子视图。最简单的技巧是在使用引用的代码之前添加一个 setTimeout。更好的解决方案是不使用视图子组件并通过 HTML 进行通信,以便 Angular 在渲染时设置您的输入,而不是从控制器/组件中进行
标签: javascript angular typescript rxjs ngrx