async ngOnInit() { if (this.mobileLayerService.earthStoryJson.length == 0) await this.mobileLayerService.earthStoryInit(); console.log(this.mobileLayerService.earthStoryJson,'2222222222222233333333333') }第一次页面不显示数据,第二次才显示
时间: 2024-04-21 15:22:53 浏览: 17
根据你提供的代码,问题可能出现在接口调用的异步操作上。在ngOnInit生命周期钩子函数中,你使用了`await`关键字等待`earthStoryInit()`方法完成后才继续执行后面的代码。这样做确保了接口数据已经获取到了,但可能导致首次页面不显示数据的问题。
一种解决方案是使用Angular的变更检测机制来更新组件的数据和视图。你可以尝试在接口数据获取到后手动调用`ChangeDetectorRef`的`detectChanges()`方法来触发变更检测。
首先,在组件的构造函数中注入`ChangeDetectorRef`:
```typescript
constructor(private cdr: ChangeDetectorRef) {}
```
然后,在接口数据获取到后手动触发变更检测:
```typescript
async ngOnInit() {
if (this.mobileLayerService.earthStoryJson.length == 0) {
await this.mobileLayerService.earthStoryInit();
this.cdr.detectChanges(); // 手动触发变更检测
}
console.log(this.mobileLayerService.earthStoryJson, '2222222222222233333333333');
}
```
这样做应该能够解决首次页面不显示数据的问题,并在接口数据获取后立即更新页面。
如果问题仍然存在,请提供更多关于你的代码和错误信息的细节,以便我能够更好地帮助你解决这个问题。