我掙扎,新的對象添加到JSON響應
我的樣本JSON響應如何將新的對象添加到angular2 JSON響應
{
"products": [{
"id": 1,
"name": "xyz"
}]
}
得到迴應後需要添加新對象(顯示)到相同的JSON響應
{
"products": [{
"id": 1,
"name": "xyz",
"show":false
}]
}
這是我的示例代碼
import {Component,OnInit} from '@angular/core';
import {Http, Response} from '@angular/http';
import 'rxjs/Rx';
@Component({
templateUrl:'./electronics.html'
})
export class electronicsComponent{
productListElectronics={};
productListElectronicResponse: Object;
error:Object;
constructor(private http: Http) {
this.productListElectronicResponse={};
this.error={};
http.get('../json/electronics/electronics.json').map((res: Response) =>res.json()).subscribe(res =>
{
for(var i = 0; i <= res['products'].length; i++){
res['products'][i].show=false;
}
console.log(res);
}, error => this.error = error);
}
}
但是控制檯不斷拋出下面的錯誤
ERROR TypeError: Cannot set property 'show' of undefined at SafeSubscriber.http.get.map.subscribe._this.error [as _next] (products.component.ts:22) at SafeSubscriber.__tryOrUnsub (Subscriber.ts:238) at SafeSubscriber.next (Subscriber.ts:190) at Subscriber._next (Subscriber.ts:135) at Subscriber.next (Subscriber.ts:95) at MapSubscriber._next (map.ts:80) at MapSubscriber.Subscriber.next (Subscriber.ts:95) at XMLHttpRequest.onLoad (xhr_backend.ts:104) at ZoneDelegate.invokeTask (zone.js:398) at Object.onInvokeTask (ng_zone.ts:253) at ZoneDelegate.invokeTask (zone.js:397) at Zone.runTask (zone.js:165) at XMLHttpRequest.ZoneTask.invoke (zone.js:460)
將斷點在相關線上,等它到那裏,然後例如值,如'i'或'水庫[ '產品'] [I]'。 – 2017-05-08 08:09:40