Angular:循环遍历从webservice

时间:2017-09-10 20:59:57

标签: javascript angular typescript highcharts

我正在从外部网络服务加载数据。 我的代码如下所示:

我的服务(加载restfull数据):

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class HttpService {
  constructor(private http: Http) {}

  loadDataItems(url: string) {
    return this.http.get(url)
      .map(data => {
        data.json();
        return data.json();
      });
  }
}

我的组件(我将以前的服务注入显示数据的地方):

import {Component, OnInit} from '@angular/core';
import 'rxjs/add/operator/map'
import {HttpService} from '../http.service';

import * as $ from 'jquery';
import * as Highcharts from 'highcharts';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.css'],
  providers: [HttpService]
})

export class ListComponent implements OnInit {

  dataItems: any;
  nb = 0;
  private dataUrl = 'http://localhost:3000/list';  // URL to web api

  constructor(private dataServer: HttpService ) {}
  ngOnInit() {
    this.dataServer.loadDataItems(this.dataUrl).subscribe(
      data => {
        this.dataItems = data;
        console.log(this.dataItems);
      }
    );
    for (let i = 0 ; i < this.dataItems.length ; i++) {
      if (this.dataItems.g = 'chrome') {
        this.nb++
      }
    }

    // Build the chart
      Highcharts.chart('chart2', {
        chart: {
          plotBackgroundColor: null,
          plotBorderWidth: null,
          plotShadow: false,
          type: 'pie'
        },
        title: {
          text: 'Browser market shares January, 2015 to May, 2015'
        },
        tooltip: {
          pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
        },
        plotOptions: {
          pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            dataLabels: {
              enabled: false
            },
            showInLegend: true
          }
        },
        series: [{
          name: 'Brands',
          colorByPoint: true,
          data: [{
            name: 'Microsoft Internet Explorer',
            y: 56.33
          }, {
            name: 'Chrome',
            y: 24.03,
            sliced: true,
            selected: true
          }, {
            name: 'Firefox',
            y: 10.38
          }, {
            name: 'Safari',
            y: 4.77
          }, {
            name: 'Opera',
            y: 0.91
          }, {
            name: 'Proprietary or Undetectable',
            y: 0.2
          }]
        }]
      });
  }
}

我的目的是循环接收到的对象数据的项目,我需要计算具有特定属性的数据:

  if (this.dataItems.g = 'chrome') 

但我得到一个错误,表明这没有定义:

  

this.dataItems.length

我不会使用 ngFor ngIf 过滤它,因为我想要抓住 ts 文件中的计数值< / em>,在 highchart 小部件合成器中使用它。

任何想法?

4 个答案:

答案 0 :(得分:0)

this.dataServer.loadDataItems是异步函数,它不会立即返回结果。您应该将加载的对象循环到subscribe函数:

ngOnInit() {
    this.dataServer.loadDataItems(this.dataUrl).subscribe(
      data => {
        this.dataItems = data;
        console.log(this.dataItems);
        for (let i = 0 ; i < this.dataItems.length ; i++) {
          if (this.dataItems.g = 'chrome') {
            this.nb++
          }
        }
    });
}

此外,您有if条件的错误。您应该使用===运算符代替=

答案 1 :(得分:0)

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class HttpService {
  constructor(private http: Http) {}

  loadDataItems(url: string) {
    return this.http.get(url)
      .map(data => data.json());
  }
}


import {Component, OnInit} from '@angular/core';
import 'rxjs/add/operator/map'
import {HttpService} from '../http.service';

import * as $ from 'jquery';
import * as Highcharts from 'highcharts';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.css'],
  providers: [HttpService]
})

export class ListComponent implements OnInit {

  dataItems: any;
  nb = 0;
  private dataUrl = 'http://localhost:3000/list';  // URL to web api

  constructor(private dataServer: HttpService ) {}
  ngOnInit() {
    this.dataServer.loadDataItems(this.dataUrl).subscribe(
      data => {
        this.dataItems = data;

        for (let i = 0 ; i < this.dataItems.length ; i++) {
            if (this.dataItems.g == 'chrome') {
                this.nb++
            }
        }
        console.log(this.dataItems);
      }
    );

    // Build the chart
      Highcharts.chart('chart2', {
        chart: {
          plotBackgroundColor: null,
          plotBorderWidth: null,
          plotShadow: false,
          type: 'pie'
        },
        title: {
          text: 'Browser market shares January, 2015 to May, 2015'
        },
        tooltip: {
          pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
        },
        plotOptions: {
          pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            dataLabels: {
              enabled: false
            },
            showInLegend: true
          }
        },
        series: [{
          name: 'Brands',
          colorByPoint: true,
          data: [{
            name: 'Microsoft Internet Explorer',
            y: 56.33
          }, {
            name: 'Chrome',
            y: 24.03,
            sliced: true,
            selected: true
          }, {
            name: 'Firefox',
            y: 10.38
          }, {
            name: 'Safari',
            y: 4.77
          }, {
            name: 'Opera',
            y: 0.91
          }, {
            name: 'Proprietary or Undetectable',
            y: 0.2
          }]
        }]
      });
  }
}

答案 2 :(得分:0)

像数组一样循环对象

let yourObject = {
   name: "firas",
   age: "20"
}

Object.keys(yourObject).forEach(key => {
    let valueFromObject = yourObject[key]   // firas
})

并关心

 if (this.dataItems.g = 'chrome') {   --> = change to ==
        this.nb++
 } 

答案 3 :(得分:0)

对于计数或过滤,您只需使用过滤器... 很久没有看到这样的语法可能是错的......

       var query = myArray.filter(
                       function(element){
                          return element.propert == neededValue && 
                                 element.property == otherValue;
                       }
                   );

       return query?query.length:0;
祝你好运