如何从angular2中的对象数组中获取服务响应中的第一项值

时间:2017-11-13 14:13:09

标签: angular angular2-routing angular2-services

我有一个空数字数组和

public numbers :number[] =[]; 

api响应在这里服务:

[
{"productID":1,"productName":"Phone","price":19.96},
{"productID":3,"productName":"Phones","price":18.96},
{"productID":2,"productName":"Laptop","price":2000.96
}]

需要获得第一个价格值并传递给公共号码:数字[]此处如何操作。

export class AppComponent implements OnInit {
 @ViewChild('mycanvas')canvas:ElementRef; 

public numbers :number[] =[]; 

 public products:IProduct[];
 constructor(private _productService:ProductService)
    {
    }

 ngOnInit():void{

    this._productService.getProducts().subscribe((response) => {
  console.log(this.numberss = response);


  for(let item of response)
    {     
    console.log("ff" +item.price);
    this.numbers.push(item.price); // need to get first value and assign to 
                                   array 

    }
    }),(err)=> {this.errorMsg =<any>err};

  public doughnutChartLabels:string[] = ['Mobiles', 'Laptops'];
  public doughnutChartData:number[] = this.numbers;
  public doughnutChartType:string = 'doughnut';
}

1 个答案:

答案 0 :(得分:2)

没有for循环,您可以简单地指定为,

 this.numbers.push(response[0].price); 
相关问题