在http.get()之后将结果保存在Angular 4中的数组中

时间:2017-07-06 08:29:13

标签: javascript arrays angular http-get angular-http

我从一个带有http.get()的api中检索一个对象数组。每个项目内只有一个属性:" number"。我希望该属性存储在我的app.component中的数组中。然后我将使用chart.js将该数组用作图表的数据,现在可以正常工作。我尝试了一天多,但无法弄清楚如何去做。你能告诉我吗?

data that I get from api

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 = 'app';

  nrs: any;
  count: any;
  public listNrs: Array<number> = [];

  private apiAllUrl: string = 'http://localhost:3000/api/all';
  private apiCountUrl: string = 'http://localhost:3000/api/count';
  //private apiBothUrl: string = 'http://localhost:3000/api/both';

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

  ngOnInit() {
    this.getAllNrs();
    this.getCountNrs();
    this.getDataNumbers();
    //this.getCount();
    //this.loadData();
  }

  getAllNrs() {
    this.http.get(this.apiAllUrl)
      .map((res:Response) => res.json())
      .subscribe(
        data => { this.nrs = data},
        err => console.error(err),
        () => console.log(this.nrs)
      );
  }

  getCountNrs(){
    this.http.get(this.apiCountUrl)
      .map((res:Response) => res.json())
      .subscribe(
        data => { this.count = data},
        err => console.error(err),
        () => console.log(this.count)
      );
  }

  getDataNumbers(){

  }

  //tried using jsonp
  /*loadData() {
    this.jsonp.get(this.apiAllUrl)
        .map(res => res.json())
        .subscribe(data => console.log(data));
  }*/

  /*getCount(){
    this.getAllNrs();
    for(let nr of this.nrs){
      console.log(this.nrs.nr[1]);
    }
  }*/

  newDate(days) {
    return moment().add(days, 'days');
  }

  public lineChartData:Array<any> = [
    {data: [4, 5, 56, -23, 4,], label: 'Indexer meta served links'},
  ];

  public lineChartData1:Array<any> = [
    {data: [-23, 4, 4, 5, 56], label: 'Indexer served links'},
  ];

  public lineChartData2:Array<any> = [
    {data: [4, 5, 4, 56, -23], label: 'Real-Time served links'},
  ];

  public lineChartLabels:Array<any> = ['1 Lug 2017', '2 Lug 2017', '3 Lug 2017', '4 Lug 2017', '5 Lug 2017'];

  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 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)'
    },
  ];

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

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

  public chartHovered(e:any):void {
    console.log(e);
  }
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { ChartsModule } from 'ng2-charts/ng2-charts';

/*import { DataService } from './data.service';
import { DataComponent } from './data/data.component';*/

@NgModule({
  declarations: [
    AppComponent,
    /*DataComponent*/,
  ],
  imports: [
    BrowserModule,
    HttpModule,
    ChartsModule
  ],
  providers: [/*DataService*/],
  bootstrap: [AppComponent]
})
export class AppModule { }

getAllNrs()获取一个对象数组,其中每个对象都有一个名为number的属性。

getAllCount()获取一个对象数组,其中每个对象都有一个名为count的属性。

问题在于,即使我尝试将其映射到数组中,它也会告诉我this.nrs未定义且无法获得其长度(错误:Cannot read property 'length' of undefined)。你知道为什么会这样做吗?

如果还有什么需要让我知道,我会提供。 谢谢!

2 个答案:

答案 0 :(得分:1)

您可以使用Array.maparray of object转换为array of string( or what ever)

&#13;
&#13;
var arrOfObj = [
  {
    number: 100
  },{
    number: 200
  },{
    number: 300
  },{
    number: 400
  },{
    number: 500
  },{
    number: 600
  }
];

var arrOfStr = arrOfObj.map(function(item) {
  return item.number;
});

console.log(arrOfStr);
&#13;
&#13;
&#13;

正如我评论的那样,您可以将Array.map部分直接添加到http.get().map,但要确保res.json()实际上是对象数组

this.http.get(this.apiAllUrl)
  .map((res:Response) => res.json().map(item => item.number))  // convert here
  .subscribe(
    data => { this.nrs = data},
    err => console.error(err),
    () => console.log(this.nrs)
  );

<强> Plunker demo

答案 1 :(得分:1)

在评论中,您需要在构造函数中初始化所有属性,否则它将获得undefined。即使你给它一个类型,Typescript也不能神奇地知道它的默认值。

export class AppComponent {
    title = 'app';
    nrs: any;
    count: any;
    public listNrs: Array<number> = [];
    constructor(private http: Http) {
        let now = moment.locale("it");
        //initialize your values.
        this.nrs = [];
        this.count = 0;
    }
    //other codes
}

之后,您可以使用.map()getAllNrs()

中返回一组数字
getAllNrs() {
    this.http.get(this.apiAllUrl)
        .map((res: Response) => res.json())
        .subscribe(
            data => {
                this.nrs = data.map(nrObj => nrObj.number)
            },
        );
}