Error encountered during the compilation of Angular2 Typescript due to difficulty in mapping a JSON response with underscores in the names

I recently started working with angular2 and I'm trying to map a JSON response to an array of custom objects. The issue I'm facing is that when I try to access a variable with an underscore in its name, I encounter a compile error. I followed the Tour of Heroes example for guidance.

Here's my custom object:

export class EventCount {
  event_count: number;
  name: string;
  id: string;  
}

To match the sample JSON response:

[{"event_count":10,"name":"dev-03","id":"0001"},
 {"event_count":6,"name":"dev-02","id":"0002"}]

My http.get request method looks like this:

getEventCounts(): Observable<Array<any>> {
  let headers = new Headers({ 'Content-Type': 'application/json' });
  let options = new RequestOptions({ headers: headers });
  let query = this.getEventCountURL;
  return this.http.get(query, options)
    .map(this.extractCounts)
    .catch(this.handleError);
}

The function called within the map is as follows:

private extractCounts(response: Response) {
  if (response != null) {
    try {
      let myCounts = response.json() as EventCount[];
      for (let entry of myCounts) {
        console.log("Name: " + entry.name + ", id: " + entry.id );
      }
    } catch (e) {
      console.error(e.toString());
    }
  }
  return myCounts;
}

The code above works perfectly fine and I can see the correct output in the console log.

Name: dev-03, id: 0001
Name: dev-02, id: 0002

However, when I change the logging line to:

console.log("Name: " + entry.name + ", count: " + entry.event_count );

I receive a compile error:

ERROR in .../count.service.ts: Property 'event_count' does not exist on type 'EventCount'.

In the VSCode debugger, I can clearly see that the event_count variable within the entry object is populated even when it's not being used in the log output.

Any thoughts or suggestions? Appreciate the help!

Answer №1

Upon reviewing your code, I have identified a minor issue that is quite similar to the problem encountered in the angular.io documentation on Http. The issue lies in the local definition of 'myCounts' not being accessible where it is needed for the return statement. However, once I replaced 'entry.id' with 'entry.event_count', everything worked smoothly. To solve this, I declared 'let myCounts: EventCount[]' before the 'if' statement and removed the 'as EventCount[]'. As you are new to Angular, I recommend using the latest version of the platform for better compatibility.

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

Ways to modify the datepicker format in Angular Material

I am currently facing an issue with the date format generated by the angular material datepicker...Wed Nov 21 2018 00:00:00 GMT+0530 (India Standard Time) My requirement is to receive the date in either (YYYY-MM-DD) or (YYYY-MM-DDTHH:mm) format. Here is ...

Modify the code to use a BehaviorSubject subscribing to an Observable

Currently, I am in the process of learning Angular2 and RxJS by studying someone else's application. The application consists of two modules: asObservable.ts export function asObservable(subject: Subject) { return new Observable(fn => subject ...

Transforming ActivatedRoute.queryParams into a Promise

Instead of subscribing to route.queryParams as an Observable, I want it to be a Promise so that I can use async/await for function calls in ngOnInit. However, my attempt at this is not working as expected. The code below does not produce any output: constr ...

Issue with NodeJS: The HTTP GET request is returning the code instead of the expected JSON object

My NodeJS code is designed to fetch a JSON object from a website. Here is the snippet: var http = require('http'); var url = { host: 'www.sample-website.com', headers: { "Accept": "application/json", 'Content-Type&apos ...

Encountering a dependency resolution issue in Angular application while executing npm install command

My Angular 9 (* UPDATE, should be Angular 11) project was developed on Ubuntu and Mac machines. The command npm install works perfectly fine in these environments. Now, I need to deploy it to a Linux Centos 7 server, so I decided to Dockerize the project. ...

Trouble with invoking a function within a function in Ionic2/Angular2

Currently, I am using the Cordova Facebook Plugin to retrieve user information such as name and email, which is functioning correctly. My next step is to insert this data into my own database. Testing the code for posting to the database by creating a func ...

Using Jquery Ajax in Conjunction with Spring MVC

I recently encountered an issue while trying to make an ajax query from a Spring MVC JSP page. The request was successfully made and I could see the JSON response on the browser. $.get("${pageContext.request.contextPath}/xxx.htm", {x: y}, function(result) ...

What is the process for serializing Manatee.Json.JsonValue?

One of the main classes I frequently use in my code is Manatee.Json.JsonValue. In a current scenario, I have a property that is defined as type object. This particular property has the flexibility to hold both simple values and complex types. However, whe ...

Retrieve JSON data from an external link and showcase it within a div, unfortunately encountering an issue with the functionality

Encountering the error message "XMLHttpRequest cannot load . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '' is therefore not allowed access" Check out the plunker link for more information: http ...

When using html2canvas in Angular, it is not possible to call an expression that does not have a call signature

I'm currently working on integrating the html2canvas library into an Angular 8 project. Despite trying to install the html2canvas types using npm install --save @types/html2canvas, I'm still facing issues with its functionality. Here's how ...

Having trouble importing the hash-set module in TypeScript/SystemJS?

In the midst of developing an Aurelia project with TypeScript to generate JavaScript, I decided to incorporate another custom library called 'hash-set' (installed using jspm install npm:hash-set --save). However, I encountered difficulties in act ...

Cross-Origin Resource Sharing problem with identical URL

I encountered a CORS issue with my Angular 6 application running on port 4200 and using an API on port 3000. To address this, I implemented the following code snippet on the server side: app.use(function(req, res, next) { res.header("Access-Control-Allo ...

The program encountered an error with code TS2339, indicating that the property "name" cannot be found on the type "never"

app.component.html I'm attempting to display the response data from my Firebase project using *ngFor. <div class="row"> <div class="col-md-3"> <h4 class="text-warning">All Employee Da ...

Verifying the functionality of a custom directive in Angular 2 (Ionic 2) through unit

In my ionic application, I developed a custom directive specifically for text masking, aimed at formatting phone numbers within input fields. The core functionality of this directive revolves around utilizing ngControl to facilitate the retrieval and assig ...

Error encountered in Python with JSON: List indices should be integers or slices, not strings

I'm encountering an issue while trying to retrieve the matchID from JSON data, as I'm receiving a TypeError. Can someone provide guidance on how to resolve this problem? Here's the URL: from selenium import webdriver import requests import ...

Retrieving various sets of JSON objects arrays

I have successfully stored an array of JSON objects in the database using the following code: function send_custom_markers() { var reponse = confirm("Send markers to selected contacts?"); if (reponse === true) { var json_markers = new ...

Steps for utilizing response data as parameters for useInfiniteQueryHere is how you can make

On the specific page where I am implementing useInfiniteQuery const { data, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage, status } = useInfiniteQuery( ['posts', searchState], ({ pageParam = 1 }) => post.search({ . ...

The JSON retrieval process using AJAX and a PHP proxy encounters an error at the %20 character

I am facing a minor issue. I am making an AJAX call to fetch JSON data using a PHP proxy hosted on my website. Everything works smoothly, but whenever there is an argument with a space, it gets encoded as %20 and I receive the following error: {"status":{ ...

Steps for adding a div after a specified number

To display the following div after getting a value greater than or equal to the specified value and retrieving it through ajax: 1. How can I show the below div with the given value? .mainbox{ width:auto; height:auto; padding:20px; background:#f00; } .i ...

Removing a portion of an item with the power of RxJS

I possess the subsequent entity: const myObject = { items:[ { name: 'John', age: 35, children: [ { child: 'Eric', age: 10, sex: 'M' }, { ...