Creating objects in Angular 2 through HTTP GET calls

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.

Answer №1

Another option is to utilize the arrowFunction ()=> as demonstrated in the example below,

fetchData() {
        this.services.fetchData()
            .subscribe(
            (response) => {                                       //<<<<===here
                response.forEach((element: DataAnalytics, index: number) => {
                    this.dataArray.push(
                        new DataAnalytics({
                            path: element['ga:pagePath'],
                            views: element.pageViews,
                            uniqueViews: element.uniquePageViews,
                            avgTime: element.avgTimeOnPage,
                            entrances: element.entrances,
                            bounceRate: element.bounceRate
                        })
                    );
                });
            },
            (error) => { console.log("An error occurred" + error) }, 
            () => {                                              
                console.log("Subscription complete");
            }
            );

    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Javascript and jQuery to validate strings within an array

My existing jQuery code works perfectly by returning true if it matches the specified name. jQuery(function($) { var strings = $(".user-nicename").text(); if (strings === "name1") { $('.mention-name').hide(); $('.se ...

Encountered a mistake while trying to deploy an Angular 2 application on Heroku - received an error message indicating an expected expression but instead got

I am encountering an issue with my Angular 2 app. It runs perfectly fine locally, but when I deploy it on Heroku, I'm getting the following errors: >SyntaxError: expected expression, got '<' ><!DOCTYPE html> >shim.min.js ( ...

Struggling to generate a cookie through an express middleware

I'm currently working on setting up a cookie for new user registrations in my app to track their first login attempt. I came across this thread which provided some guidance but I'm still facing issues. Below is the snippet of my code: // Middle ...

What is the best way to download the entire page source, rather than just a portion of it

I am currently facing an issue while scraping dynamic data from a website. The PageSource I obtain using the get() method seems to be incomplete, unlike when viewing directly from Chrome or Firefox browsers. I am seeking a solution that will allow me to fu ...

How to retrieve TypeScript object within a Bootstrap modal in Angular

Unable to make my modal access a JavaScript object in the controller to dynamically populate fields. Progress Made: Created a component displaying a list of "person" objects. Implemented a functionality to open a modal upon clicking a row in the list. ...

Updating state based on input from a different component

I am attempting to modify the state of the page index in index.js from the Pagination component, Here is my index.js code: import useSWR from 'swr'; import { useState } from 'react'; const Index = ({ data }) => { const ini ...

Why does Javascript execute in this specific order?

I'm puzzled as to why JavaScript behaves in a certain way, or if I made an error in my code. How is it that the code after $.getJSON runs before the callback completes? window.ratingCallback = function(data){ if(data[0].code == 3){ ratin ...

Angular 4, Trouble: Unable to resolve parameters for StateObservable: (?)

I've been working on writing unit tests for one of my services but keep encountering an error: "Can't resolve all parameters for StateObservable: (?)". As a result, my test is failing. Can someone please help me identify and fix the issue? Here& ...

Tips on transferring dynamically generated results to a user-friendly print window

After users complete a quiz, they receive their results. The client now wants to implement a "Print Results" feature that opens in a new window with customized CSS. I'm trying to figure out how to transfer the results to the new window using JavaScri ...

js.executeScript produces a Unexpected identifier error

Visit this link for proofs Running a script in the browser console on the specified page: let img = document.querySelector('.subscribe'), style = img.currentStyle || window.getComputedStyle(img, false), bi = style.backgroundImage.slice(4, -1).re ...

Tips for ensuring the angular FormArray is properly validated within mat-step by utilizing [stepControl] for every mat-step

When using Angular Material stepper, we can easily bind form controls with form groups like [stepControl]="myFormGroup". But how do we bind a FormArray inside a formGroup? Constructor constructor(private _fb: FormBuilder){} FormArray inside For ...

`We enhance collaboration within sibling next components by exchanging information`

Completely new to web development, I have been working on an app with a navbar that allows users to select items from a drop-down menu. My specific issue is trying to access the title.id in a sibling component, but it keeps coming up as null. PARENT COMPO ...

The WebView.HitTestResult method is currently only receiving <img src> elements and not <a href> elements

I am attempting to open a new window in the Android browser using "_blank". I have set up an event listener for this purpose. mWebView.getSettings().setSupportMultipleWindows(true); mWebView.setWebChromeClient(new WebChromeClient() { ...

What is the process for deleting a token from local storage and displaying the logout page in Next JS?

I developed a Next.js web application and am looking to display a logout page when the token expires, while also removing the expired token from local storage. How can I ensure that this functionality works no matter which page the user visits within the a ...

Using multiple jQuery dialogs on index.php

I have a vision for my website to mirror the Windows environment, complete with icons that prompt dialog boxes when clicked. On my site's index page, I've added the following code within the head tags: <link rel="stylesheet" href="http://cod ...

Typescript: searching for a specific type within an array of objects

The title may be a bit unclear, but I'm struggling to find a better way to explain it. I have a predefined set of classes from a third-party library that I cannot modify. The specific content of these classes is not relevant, as it's just for i ...

Having trouble hiding the message "Not found" with ng-hide and filters in AngularJS

I am currently working on incorporating instant search functionality with filters in AngularJS. My goal is to have the "Not Found!!" message displayed when the filter results in an empty array, indicating that no matches were found. However, I have encou ...

What is the reason behind starting certain scripts using "npm start x" while others only require "npm x"?

Within the package.json file, I have included a section dedicated to defining scripts for various tasks: "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build --prod", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e" }, ... When lau ...

"Enhance Your Browse experience: Chrome Extension that automatically appends content to pages

I'm currently developing a Chrome extension that detects when a URL on a specific domain changes, and if the URL matches a certain pattern, it will add new HTML content to the webpage. Here is an excerpt from my manifest.json file: { "name": "Ap ...

Retrieving information from an openDatabase using AngularJS

Encountering an issue while trying to retrieve data from openDatabase and display it in a listview. Following advice from a thread, I added $scope.$apply(); after $scope.items = $data;, but this resulted in an error: [$rootScope:inprog] $apply already in p ...