如何将*ngIf用于异步http.get数据请求-Angular 2

如何将*ngIf用于异步http.get数据请求-Angular 2,angular,http-get,Angular,Http Get,我有一个web应用程序,它正在从多个api检索数据,并且应该使用这些数据生成一些图表。问题在于,当图表呈现出来时,api中的数据还没有出现。我尝试使用.then()方法,但它告诉我类型void上不存在属性。此外,我尝试使用ngIf方法,如下所示,但也不起作用。你知道我怎么解决这个问题吗 下面是我的组件和我的组件模板 app.component.ts import { Component } from '@angular/core'; import { Http, Response } from

我有一个web应用程序,它正在从多个api检索数据,并且应该使用这些数据生成一些图表。问题在于,当图表呈现出来时,api中的数据还没有出现。我尝试使用
.then()
方法,但它告诉我类型void上不存在
属性。此外,我尝试使用
ngIf
方法,如下所示,但也不起作用。你知道我怎么解决这个问题吗

下面是我的组件和我的组件模板

app.component.ts

import { Component } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/Rx';

import * as moment from 'moment'; 

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Mimesi dashboard graphs';

  //COUNTS
  public countIndexerMetaApi; //array of one number populated from http.get
  public countIndexerMetaNumber; //number extracted into array and stored as an int
  public countIndexerMetaArray; //array to store countNumber afterwards

  public countIndexerServedApi; 
  public countIndexerServedNumber; 
  public countIndexerServedArray; 

  public countRealTimeServedApi; 
  public countRealTimeServedNumber; 
  public countRealTimeServedArray;

  //DATES
  public dateIndexerMetaToStore; //date got from moment method that needs to be stored
  public dateIndexerMetaArray; //array to store dates for graph label

  public dateIndexerServedToStore;
  public dateIndexerServedArray;

  public dateRealTimeServedToStore;
  public dateRealTimeServedArray;

  //API LINKS
  private apiCountIndexerMetaUrl: string = 'http://localhost:3000/api/countIndexerMetaApi';
  /*      TODO - API FOR COUNT OF OTHER TWO TABLES      */
  private apiCountIndexerServedUrl: string = 'http://localhost:3000/api/countIndexerServedApi';
  private apiCountRealTimeServedUrl: string = 'http://localhost:3000/api/countRealTimeServedApi';

  //VARIABLE FOR TIMEOUT
  public isDataAvailable:boolean = false;

  constructor(private http:Http) { 
    let now = moment.locale("it");

    //COUNT
    this.countIndexerMetaApi = 0;
    this.countIndexerMetaNumber = 0;
    this.countIndexerMetaArray = [];

    this.countIndexerServedApi = 0;
    this.countIndexerServedNumber = 0;
    this.countIndexerServedArray = []

    this.countRealTimeServedApi = 0;
    this.countRealTimeServedNumber = 0;
    this.countRealTimeServedArray = []

    //DATES
    this.dateIndexerMetaToStore = "";
    this.dateIndexerMetaArray = [];

    this.dateIndexerServedToStore = "";
    this.dateIndexerServedArray = [];

    this.dateRealTimeServedToStore = "";
    this.dateRealTimeServedArray = [];
  }

  ngOnInit() {
    this.getIndexerMetaCount();
    this.getIndexerServedCount();
    this.getRealTimeServedCount();
  }

  //COUNT
  getIndexerMetaCount(){
    this.http.get(this.apiCountIndexerMetaUrl)
        .map((res: Response) => res.json())
        .subscribe(
            data => {
                console.log(this.countIndexerMetaApi = data.map(countIndexerMetaApiObj => countIndexerMetaApiObj.countIndexerMetaApi))
            },
        );
    //this.countIndexerMetaNumber = this.countIndexerMetaApi[0]; //<-- timing problem since this.count is not yet got from http.get() so it seems undefined
    //this.countIndexerMetaArray.push(this.countIndexerMetaNumber); // problem follows through
  }
  printCountIndexerMetaArray(){
    this.countIndexerMetaApi.forEach(element => {
      console.log(element);
    });
  }

  getIndexerServedCount(){
    this.http.get(this.apiCountIndexerServedUrl)
        .map((res: Response) => res.json())
        .subscribe(
            data => {
                console.log(this.countIndexerServedApi = data.map(countObj => countObj.countIndexerServedApi))
            },
        );
    //this.countIndexerServedNumber = this.countIndexerServedApi[0]; //<-- timing problem since this.count is not yet got from http.get() so it seems undefined
    //this.countIndexerServedArray.push(this.countIndexerServedNumber); // problem follows through
  }
  printCountIndexerServedArray(){
    this.countIndexerServedApi.forEach(element => {
      console.log(element);
    });
  }

  getRealTimeServedCount(){
    this.http.get(this.apiCountRealTimeServedUrl)
        .map((res: Response) => res.json())
        .subscribe(
            data => {
                console.log(this.countRealTimeServedApi = data.map(countObj => countObj.countRealTimeServedApi))
            },
        );
    //this.countRealTimeServedNumber = this.countRealTimeServedApi[0]; //<-- timing problem since this.count is not yet got from http.get() so it seems undefined
    //this.countRealTimeServedArray.push(this.countRealTimeServedNumber); // problem follows through
  }
  printRealTimeServedArray(){
    this.countRealTimeServedApi.forEach(element => {
      console.log(element);
    });
  }

  //DATES
  dateIndexerMeta() {
    this.dateIndexerMetaToStore = moment().add(-122, 'days');
    this.dateIndexerMetaArray.push(this.dateIndexerMetaToStore);
  }

  dateIndexerServed() {
    this.dateIndexerServedToStore = moment().add(-122, 'days');
    this.dateIndexerServedArray.push(this.dateIndexerServedToStore);
  }

  dateRealTimeServed() {
    this.dateRealTimeServedToStore = moment().add(-122, 'days');
    this.dateRealTimeServedArray.push(this.dateRealTimeServedToStore);
  }

  //TIMEOUT TRIAL
  timeoutTrial(){
    console.log(this.isDataAvailable);
    setTimeout(function() {this.isDataAvailable = true; 
      console.log(this.isDataAvailable);
    }, 5000); //<-- timeout works but other functions don't refresh even if isDataAvailable changed
  }

  /*      CHARTS      */

  //DATA
  public lineChartData:Array<any> = [
    {data: this.countIndexerMetaArray, label: 'Indexer meta served links'},
  ];

  public lineChartData1:Array<any> = [
    {data: this.countIndexerServedArray, label: 'Indexer served links'},
  ];

  public lineChartData2:Array<any> = [
    {data: this.countRealTimeServedArray, label: 'Real-Time served links'},
  ];

  //LABELS
  public lineChartLabels:Array<any> = this.dateIndexerMetaArray;

  public lineChartLabels1:Array<any> = this.dateIndexerServedArray;

  public lineChartLabels2:Array<any> = this.dateRealTimeServedArray; 

  //OPTIONS
  public lineChartOptions:any = {
    responsive: true,

    scales: {
      xAxes: [{
        type: 'time',
        time: {
          displayFormats: {
            'millisecond': 'DD MMM',
            'second': 'DD MMM',
            'minute': 'DD MMM',
            'hour': 'DD MMM',
            'day': 'DD MMM',
            'week': 'DD MMM',
            'month': 'DD MMM',
            'quarter': 'DD MMM',
            'year': 'DD MMM',
          }
        }
      }],
    },

  };

  public lineChartLegend:boolean = true;
  public lineChartType:string = 'line';

  //COLORS
  public lineChartColors:Array<any> = [
    { // grey
      backgroundColor: 'rgba(255,55,55,0.2)',
      borderColor: 'rgba(255,55,55,1)',
      pointBackgroundColor: 'rgba(255,55,55,1)',
      pointBorderColor: '#fff',
      pointHoverBackgroundColor: '#fff',
      pointHoverBorderColor: 'rgba(255,55,55,0.8)'
    },
  ];

  //EVENTS
  public chartClicked(e:any):void {
    console.log(e);
  }

  public chartHovered(e:any):void {
    console.log(e);
  }
}
从'@angular/core'导入{Component};
从'@angular/Http'导入{Http,Response};
从'rxjs/Rx'导入{Observable};
进口“rxjs/Rx”;
从“时刻”导入*作为时刻;
@组成部分({
选择器:'应用程序根',
templateUrl:“./app.component.html”,
样式URL:['./app.component.css']
})
导出类AppComponent{
标题='Mimesi仪表板图';
//计数
public countIndexerMetaApi;//从http.get填充的一个数字的数组
public countIndexerMetaNumber;//提取到数组中并存储为int的数字
public CountIndexer MetaArray;//用于存储countNumber的数组
公共countIndexerServedApi;
公共countIndexerServedNumber;
公共CountIndexerServeArray;
公共countRealTimeServedApi;
公共countRealTimeServedNumber;
公共国家实时服务阵列;
//日期
public DateIndexer MetaToStore;//从需要存储的矩方法获取的日期
public dateIndexerMetaArray;//用于存储图形标签日期的数组
公共日期索引器服务的数据库;
公共日期索引服务阵列;
公共dateRealTimeServedToStore;
公共DateRealTimeServeArray;
//API链接
私有apiCountIndexerMetaUrl:string=http://localhost:3000/api/countIndexerMetaApi';
/*TODO-其他两个表计数的API*/
私有apiCountIndexerServedUrl:string='1〕http://localhost:3000/api/countIndexerServedApi';
private ApicountRealTimeServeUrl:string='1〕http://localhost:3000/api/countRealTimeServedApi';
//超时变量
public isDataAvailable:boolean=false;
构造函数(专用http:http){
let now=moment.locale(“it”);
//计数
this.countIndexerMetaApi=0;
this.countIndexerMetaNumber=0;
this.countIndexerMetaArray=[];
this.countIndexerServedApi=0;
this.countIndexerServedNumber=0;
this.countIndexerServeArray=[]
this.countRealTimeServedApi=0;
this.countRealTimeServedNumber=0;
this.countRealTimeServedArray=[]
//日期
this.dateIndexerMetaToStore=“”;
this.dateIndexerMetaArray=[];
this.dateIndexerServedToStore=“”;
this.dateIndexerServeArray=[];
this.daterealtimeservedtore=“”;
this.dateRealTimeServeArray=[];
}
恩戈尼尼特(){
this.getIndexerMetaCount();
this.getIndexerServedCount();
这是.getRealTimeServedCount();
}
//计数
getIndexerMetaCount(){
this.http.get(this.apiCountIndexerMetaUrl)
.map((res:Response)=>res.json())
.订阅(
数据=>{
log(this.countIndexerMetaApi=data.map(countIndexerMetaApiObj=>countIndexerMetaApiObj.countIndexerMetaApi))
},
);
//this.countIndexerMetaNumber=this.countIndexerMetaApi[0];//{
控制台日志(元素);
});
}
getIndexerServedCount(){
this.http.get(this.apiCountIndexerServedUrl)
.map((res:Response)=>res.json())
.订阅(
数据=>{
log(this.countIndexerServedApi=data.map(countObj=>countObj.countIndexerServedApi))
},
);
//this.countIndexerServedNumber=this.countIndexerServedApi[0];//{
控制台日志(元素);
});
}
getRealTimeServedCount(){
this.http.get(this.apiCountRealTimeServedUrl)
.map((res:Response)=>res.json())
.订阅(
数据=>{
log(this.countRealTimeServedApi=data.map(countObj=>countObj.countRealTimeServedApi))
},
);
//this.countRealTimeServedNumber=this.countRealTimeServedApi[0];//{
控制台日志(元素);
});
}
//日期
dateIndexerMeta(){
this.dateIndexerMetaToStore=moment().add(-122,'days');
this.dateIndexerMetaArray.push(this.dateIndexerMetaToStore);
}
日期索引器(){
this.dateIndexerServedToStore=moment().add(-122,'days');
this.dateIndexerServedArray.push(this.dateIndexerServedToStore);
}
dateRealTimeServed(){
this.daterealtimeservedtore=moment().add(-122,'days');
this.dateRealTimeServedArray.push(this.dateRealTimeServedToStore);
}
//超时试验
超时试验(){
console.log(this.isDataAvailable);
setTimeout(函数(){this.isDataAvailable=true;
console.log(this.isDataAvailable);

},5000);//U忘了它[

请尝试为此组件使用解析程序
[

只需使用布尔值来显示加载

public isloading = true; 
在http调用中,一旦获得所需的所有数据,就将其设置为false

this.http.get(this.apiCountRealTimeServedUrl)
        .map((res: Response) => res.json())
        .subscribe(
            data => {
                this.countRealTimeServedApi = 
                    data.map(countObj => countObj.countRealTimeServedApi);
                this.isloading= false;
            },
        );
在HTTP中,为isloading部分设置
ngIf

<div *ngIf="isloading" > loading .... </div>
<div *ngIf="!isloading" > 
   <!-- show the chart contents -->
</div>

我不明白你到底有什么问题,请你再澄清一点好吗。 但是如果你的问题是这些线路

this.countIndexerServedNumber = this.countIndexerServedApi[0]; 
  //<-- timing problem since this.count is not yet 
  // got from http.get() so it seems undefined
this.countIndexerServedArray.push(this.countIndexerServedNumber); 
   // problem follows through
this.countIndexerServedNumber=this.countIndexerServedApi[0];

//代码太多。您是否尝试过
*ngIf=“items | async as mydata”
*ngFor=“item of mydata”内部
?其中
在一个承诺中应该解决一个iterable。对不起,不起作用的部分是
lineChartData
变量,顶部的三个循环很好。不管怎样,试着像他说的那样:
*ngIf=“items | async”
*ngIf=“items | async as mydata”
抱歉,我对angular非常陌生,我尝试过实现它,但它不起作用,或者可能是我做错了。你知道我应该如何实现它吗?谢谢你的回答。问题解决了
<div *ngIf="isloading" > loading .... </div>
<div *ngIf="!isloading" > 
   <!-- show the chart contents -->
</div>
 <div *ngIf="isIndexMetaCountloading 
            || isIndexerServedCountLoading 
            || isRealTimeServedCountLoading" > 
   loading ...
</div>

<div *ngIf="!isIndexMetaCountloading 
            && !isIndexerServedCountLoading 
            && isRealTimeServedCountLoading" > 
   <!-- show the chart contents -->
</div>
this.countIndexerServedNumber = this.countIndexerServedApi[0]; 
  //<-- timing problem since this.count is not yet 
  // got from http.get() so it seems undefined
this.countIndexerServedArray.push(this.countIndexerServedNumber); 
   // problem follows through