我已經開始學習angular 2.我嘗試通過http get request獲取一些數據,然後我想用這些數據創建對象,以便稍後可以使用模板顯示它們。如果我用錯誤的方式思考,你可以告訴我。Angular 2從http獲取請求的對象獲取請求
我有我的模型AnalyticsData:
export class AnalyticsData {
pagePath: string;
pageViews: number;
uniquePageViews: number;
avgTimeOnPage: number;
entrances: number;
bounceRate: number;
constructor(object?: any) {
this.pagePath = object && object.pagePath || null;
this.pageViews = object && object.pageViews || null;
this.uniquePageViews = object && object.uniquePageViews || null;
this.avgTimeOnPage = object && object.avgTimeOnPage || null;
this.entrances = object && object.entrances || null;
this.bounceRate = object && object.bounceRate || null;
}
}
我的DataService:
export class DataService {
private dataUrl: string = 'http://example.com/app/analyticsdata';
constructor(private http: Http) { }
getData() {
return this.http.get(this.dataUrl)
.map((response: Response) => response.json());
}
}
我AnalyticsComponent:
export class AnalyticsComponent implements OnInit {
myData: Array<AnalyticsData>;
constructor(private services: DataService) { }
ngOnInit(): void {
this.getData();
}
getData() {
this.services.getData()
.subscribe(
function (response) {
response.forEach((element: AnalyticsData, index: number) => {
this.myData.push(
new AnalyticsData({
pagePath: element['ga:pagePath'],
pageViews: element.pageViews,
uniquePageViews: element.uniquePageViews,
avgTimeOnPage: element.avgTimeOnPage,
entrances: element.entrances,
bounceRate: element.bounceRate
})
);
});
},
function (error) { console.log("Error happened" + error) },
function() {
console.log("the subscription is completed");
}
);
}
}
與上述錯誤是:EXCEPTION: Cannot read property 'push' of undefined
。我不明白爲什麼會發生這種情況,因爲我已經在課程頂部分配了變量myData
。
'myData的:數組;' –
micronyks
此添加到你的構造並再次嘗試:'this.MyData = [];' –
@HarryNinh謝謝我將你的答案和micronyks答案結合起來解決我的問題。 – amrfs