Recently, I've delved into learning Angular 2. My current challenge involves making http get requests to retrieve data and then constructing objects from that data for later display using templates. If you believe my approach is incorrect, please feel free to provide feedback.
I have created a model called 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;
}
}
This is my 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());
}
}
The AnalyticsComponent code snippet is as follows:
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("An error occurred: " + error) },
function () {
console.log("Subscription completed successfully");
}
);
}
}
An issue encountered in the above code is:
EXCEPTION: Cannot read property 'push' of undefined
. I'm puzzled by this error because the variable myData
is clearly declared at the beginning of the class.