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

Looking to access a component property from another component in Angular 14 – how can I do that?

I am facing a challenge where I need to access a string property from another component without displaying it in the html file. While searching for solutions, I come across references to *ngIf/ngFor, but those don't seem applicable to my scenario. My ...

The Swift HTTP request is missing any post data

When attempting to send post data via http to the server, it seems that no post data is being returned. Below is a snippet of the code I used: var request = URLRequest(url: URL(string: "http://posttestserver.com/post.php")!) request.httpMethod = "POST" re ...

Looking for assistance with parsing C# / .NET 6 into individual objects

I am currently working with the JsonSerializer.Deserialize() method from the System.Text.JSON library in .NET 6. The JSON format is beyond my control. While I have successfully used this method before, the data I'm dealing with now is slightly more ...

(Enhancing Angular) Capture HttpResponse errors and seamlessly proceed with the Observable

There's a dropdown text box with type-ahead search functionality. Valid item names prompt the expected list of items in the drop-down menu, while invalid entries trigger a 400 error response from the API. This error is caught by the HttpErrorIntercept ...

Clicking on the button in Angular 2+ component 1 will open and display component 2

I've been developing a Angular 4 application with a unique layout consisting of a left panel and a right panel. In addition to these panels, there are 2 other components within the application. The left panel component is equipped with buttons while ...

The image fetched from an API is not appearing within the pageview container in a Swift application

I have been developing an iOS app that communicates with an API using Alamofire and SwiftyJSON. The API returns various values, including a collection of images. I have successfully managed to iterate through the array of images and display them individual ...

Is it possible to save an externally retrieved image locally using Angular?

I'm brand new to Angular and trying to work with a QR code image generated from the angularx-qrcode library. Here is the code snippet: <qrcode [qrdata]="'Your QR code data string'" [size]="256" [level]="'M'"></qrcode> ...

Working with JSON data through the command line interface (CLI) with

Imagine you have the following JSON object: { "d": { "e": { "bar": 2 } }, "a": { "b": { "c": { "foo": 1 } } } } You want to access the value of foo without having to type '.a.b.c.foo'. You migh ...

Preventing the upload of empty images in an angular application

When selecting multiple images for upload, I sometimes need to make changes or delete the chosen images before actually uploading them. However, if any of the selected images have a size of 0B, I want to stop the upload process for all images, not just the ...

Bring in personalized tag to TypeScript

I am working on a TypeScript file to generate an HTML page. Within this code, I want to import the module "model-viewer" and incorporate it into my project. import * as fs from "fs"; import prettier from "prettier"; import React from "react"; import ReactD ...

What is the process of transforming a basic JavaScript function into a TypeScript function?

As a Java developer diving into TypeScript for frontend development, I've encountered a simple JavaScript code snippet that I'd like to convert to TypeScript. The original JavaScript code is: let numbers = [123, 234, 345, 456, 567]; let names = ...

Toggle the visibility of the navigation bar in Angular based on the user

I have implemented rxjs BehaviorSubject in my login page to transmit data to auth.service.ts, enabling my app.component to access the data stored in auth.service.ts. However, I now require the app.component to detect any changes made to the data in auth.se ...

Differences Between APP_INITIALIZER and platformBrowserDynamic with provide

I've discovered two different approaches for delaying an Angular bootstrap until a Promise or Observable is resolved. One method involves using APP_INITIALIZER: { provide: APP_INITIALIZER, useFactory: (configService: ConfigurationService) => ( ...

Oops! An issue occurred: [RunScriptError]: Running "C:Windowssystem32cmd.exe /d /s /c electron-builder install-app-deps" resulted in an error with exit code 1

query: https://github.com/electron/electron/issues/29273 I am having trouble with the installation package as it keeps failing and showing errors. Any tips or suggestions would be highly appreciated. Thank you! ...

What is the method for retrieving service values in Angular2?

I've been following the Angular2 tutorial steps at this link: https://angular.io/docs/ts/latest/tutorial/toh-pt4.html There's a particular syntax used to return service promise information back to the component, as shown here: getHeroes() { t ...

What is the best way to transfer data from form input fields to a script with AJAX and jQuery?

Here is the current structure of my code. Main File: index.php <script type="text/javascript" src="jquery-1.4.2.js"></script> <script type="text/javascript" src="ajax.js"></script> <select id="dropdown_id"> <option valu ...

Gatsby no longer hosts the website locally during certain tasks

My React and Gatsby project runs smoothly when I use Yarn start, it builds everything and serves the project on http://localhost:8000. However, whenever I perform specific operations like going to a 404 page or opening Chrome Dev tools, it suddenly stops s ...

Angular2's Dynamic Forms

When attempting to incorporate FormsArray into my Project using ReactiveFormsModule, I encountered an error message stating: Cannot find control with unspecified name attribute. Is it possible to add FormsArray in template driven forms? Here is the code ...

Tips for incorporating a child's cleaning tasks into the parent component

I am working with a parent and a child component in my project. The parent component functions as a page, while the child component needs to perform some cleanup tasks related to the database. My expectation is that when I close the parent page/component, ...

Extracting information from wikiarticle JSON. Unexpected JSON output

When parsing all sections of a wikiarticle, everything usually goes smoothly. However, I've encountered a specific issue that I can't seem to troubleshoot: Requesting restpoint 1 works perfectly and gives me the section structured as JSON: http ...