当 ngOnInit() 中未获取数据时,页面一个接一个地加载

Pages loading on top one another when data not fetched in ngOnInit()

从放置在 app.componment 的侧边菜单路由到页面时出现异常行为。 当页面加载数据时,在 ngOnInit()

中从远程服务器调用
 ngOnInit() {
    // Fecth data using service, retuns only oe row so departmentTransfion mut be type any and not array[]
    this.searching= true;
    this.service.getDepartment('Transfusion').subscribe(data => {
      this.departmentTransfusion = data;
      this.searching = false;
    })
  }

数据引用在我的page.html:

  <ion-row  style="padding-left: 4px;">
    <ion-col>
      <h3>General Infomration <ion-icon name="information-circle-outline"></ion-icon></h3>
      
      <p class="preference-value">
        {{departmentHaematology.general}}
      </p>
      <h4 class="preference-name">Opening hours <ion-icon name="hourglass-outline"></ion-icon> </h4>
      <p class="preference-value">
        
       {{departmentHaematology.openingHours}}
      </p>
    </ion-col>

当 Web 控制台中出现错误时,从侧边菜单路由的页面似乎相互重叠:

TypeError: undefined is not an object (evaluating 'ctx.departmentHaeamtology.general'

网络浏览器中重叠的页面:

所以我的问题是,重叠视图是否是由于在呈现视图之前未在 ngOnIt() 中加载数据造成的?我的理解是视图不会在 ngOnInit() 执行之前呈现,因此这种方法非常适合从远程服务器下载数据。

引用生命周期中的 angular docs

An ngOnInit() is a good place for a component to fetch its initial data.

那么这种不寻常的重叠渲染是否可能是由于在视图渲染之前未捕获数据造成的?如果是这样,那么我们应该使用生命周期的哪一部分在视图呈现之前从远程服务器捕获数据?

解决方案:

使用 angular ngIf else 显示离子旋转器,直到加载数据。 解决了页面渲染异常

<!--Seraching spinner-->
        <div *ngIf="searching; else elseBlock">
          <ion-spinner class="spinner-container" name="bubbles" color="dark"></ion-spinner>
        </div>

        <ng-template #elseBlock>

你的问题是完全正常的。问题是 HTTP 请求是异步的,它可能需要 .. 例如 0.2 秒才能完成(取决于服务器、连接等)。

独立于在构造函数或 ngOnInit 中发出请求,视图将在对服务器的请求完成之前显示。稍后,请求将完成,然后您设置变量值并刷新视图。

您的问题是第一次呈现视图时,对服务器的请求尚未完成,因此 departmentHaeamtology 为 null(空)。您的 HTML 正在尝试访问空变量的 属性“一般”,这就是错误发生的原因。

该问题的解决方案是将 *ngIf="departmentHaeamtology" 添加到页面容器。然后,在变量具有值之前,视图不会显示。那么问题是在请求完成之前您将得到一个空白页面。它可能很快,但无论如何您都会看到“弹出”效果。一个解决方案是添加一个带有 CSS.

的加载圆

关于您的页面表现怪异,可能是由于错误。当 HTML 文件中有错误时,ionic 会产生奇怪的东西。尝试我的解决方案并检查。