首页 > 解决方案 > 如何在角度加载 json 数据时添加加载器

问题描述

这是我获取角度数据的代码,我试图让它对用户更友好,加载需要一段时间,我正在寻找一种方法来添加角度加载器我是角度新手。

我正在使用 ionic cli 通过 json 数据构建移动应用程序提要

    import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";

@Component({
  selector: 'app-articlespage',
  templateUrl: './articlespage.page.html',
  styleUrls: ['./articlespage.page.scss'],
})
export class ArticlespagePage implements OnInit {


    //id : any[];
    title : any[];
    author : any[];
    date : any[];
    content : any[];

  constructor(private dataService: DataService) { }

  ngOnInit() {
    this.dataService.getRemoteData().subscribe(data => {
      console.log("Remote Data:" + JSON.stringify(data));
      //console.log(data);
      this.parseJson(data);
    });
  }

  parseJson(data)
  {
     let jsonArray = data;

    //this.id = [];
    this.title = [];
    this.author = [];
    this.date = [];
    this.content = [];

    for(let i=0; i< jsonArray.length ; i++)
    {
       let jsonObject = jsonArray[i];
       //this.id.push(jsonObject.id);
       this.title.push(jsonObject.title);
       this.author.push(jsonObject.author.name);
       this.date.push(jsonObject.created_at );
       this.content.push(jsonObject.blog_entry );

    }
  }



}

html:

  <ion-content fullscreen>
     <h2 > Articles </h2>
      <ion-card class="feedspotcard-1 box" *ngFor=" let item of title; let i = index;">
        <ion-card-content>
            <div class="box-shadow">
              <div class="coolbar"></div>
              <!-- <p> <span> Id : </span> <span innerHTML={{id[i]}}> </span> </p> -->
              <h4> <span innerHTML={{title[i]}}> </span> </h4>
              <p>  <span innerHTML={{content[i]}}> </span> </p>
              <p> <span> author : </span> <span innerHTML={{author[i]}}> </span> </p>
              <p> <span> date : </span> <span innerHTML={{date[i]}}> </span> </p>
            </div>
        </ion-card-content>
      </ion-card>
    </ion-content>

没有必要,但结果:

在此处输入图像描述

标签: jsonangularspinnerloader

解决方案


您需要一个跟踪请求状态的属性。即loadingData: boolean

在您的组件中,您需要在请求开始时以及完成时设置此值。

ngOnInit(): void {
  this.loading = true;
  this.dataService.getRemoteData().subscribe(data => {
    // set the status of loading to false so the template can update
    this.loading =f alse;
    console.log("Remote Data:" + JSON.stringify(data));
    //console.log(data);
    this.parseJson(data);
  });
}

最后,在模板中,添加一个基于loading属性值显示的元素。

<div *ngIf="loading"><!-- Insert your progress message/animation --> </div>

推荐阅读