Angular 2 interprets my JSON object as a function

My webapp retrieves data via Json and places it in objects for display. I have successfully implemented this process twice using services and classes. However, when I recently copied and pasted the old code with some modifications to redirect to the correct classes, I noticed that I am now receiving an array of functions instead of an array of objects.

https://i.sstatic.net/lwpdm.png

https://i.sstatic.net/7hCmi.png

Below is my constructor that utilizes the service classes and outputs to the console:

constructor(private featureService : FeatureService, private scenarioservice : ScenarioService, private failuresService : FailuresService){
    // Retrieving features and failures
    this.featureService.getFeatures().subscribe(res => {
      this.featureArray = res.getFeatureArray();
      console.log(res.getFeatureArray());
    });
      this.failuresService.getFailures().subscribe(res => {
      this.failureArray = res.getFailureArray();
      console.log(res.failures[0].method);
      console.log(this.failureArray);
    });

  }

}

Here is the implementation of failuresService.getFailures:

import { Injectable } from "@angular/core";
import {Http, Response} from "@angular/http";
import {Failure} from "./Failure";
import {Failures} from "./failures";


@Injectable()
export class FailuresService {
  constructor(protected http: Http) {}


  getFailures() {
    return this.http.get('http://localhost:8080/testresultaten')
      .map((response: Response) => response.json())
      .map(({failures = [Failure]}) => new Failures(failures));// Ignore this error message
  }
}

Below is the Json structure that I receive and aim to parse into a class:

{
  "failures:": [
    {
      "method": "canRollOneGame",
      "object": "BowlingGame.GameTest"
    },
    {
      "method": "canCountNighteeneight",
      "object": "FizzBuzz.FizzBuzzTest"
    }
  ]
}

And here are the Failure and Failures classes:

import {Failure} from "./Failure";
export class Failures {

  constructor(public failures : Failure[]){}
  public getFailureArray(): Failure[]{
    return this.failures;
  }

}


export class Failure{

  constructor(public method : String , public object : String ){  }
}

Answer №1

Maybe my interpretation is wrong, but this doesn't seem to be correct:

getFailures() {
    return this.http.get('http://localhost:8080/testresultaten')
      .map((response: Response) => response.json())
      .map(({failures = [Failure]}) => new Failures(failures));// this error message is not valid
  }

I'm not entirely certain about the purpose of that last mapping function. The syntax used ({failures = [Failure]}) is unfamiliar to me. While I understand that you are working with an incoming array, the way it's written might not achieve what you intend.

You could try the following approach to see if it yields a different outcome:

.map(failures => { console.log ( failures ); new Failures(failures) } );// this error message is not valid

If you compare the results between your original mapping and this suggested one by checking the console.log output, you might observe interesting differences. It's possible that the current implementation won't display the expected results.

If this adjustment resolves the issue, you can experiment with parsing the incoming payload (even though it should already be in JSON format from the previous mapping operation).

.map( (failures: Array<Failure>) => { console.log ( failures ); new Failures(failures) } );

Answer №2

It seems that your objective is to generate an array of Failure objects using data from a JSON array, each with a method you wish to implement elsewhere in the code.

If this is correct, I believe I understand the issue. As mentioned by Tim Consolazion in the comments, you are only retrieving the values for the Failure object, not the actual Failure object itself (refer to custom created method error: "is not a function"). To execute the commands associated with the Failure, you need to create a new Failure object for each item in your JSON array. Here's an example:

return this.http.get('http://localhost:8080/testresultaten')
  .map((response: Response) => {
      let content = response.json();
      let failureList: Failure[] = [];

      content.forEach(failure => {
                failureList.push(new Failure(failure.method, failure.object))
            });

      return failureList || {};
  }

I'm curious about where you came across {failures = [Failure]}. This syntax is unfamiliar to me, and I am unsure of its purpose.

EDIT: I have made adjustments to align the question with your class Failure. The variable failure in content.forEach(failure => { refers to an object within your JSON array, allowing you to access its values like a typical object. In your case, these would be failure.method and failure.object.

Answer №3

While analyzing the Json data, I identified an issue with the spelling of the key "function:". In my code, it was spelled as "function". The solution was to ensure that it sends "function" instead of "function:".

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

Different ways to reference a variable in Typescript without relying on the keyword "this" throughout the codebase

Can we eliminate the need to write "this" repeatedly, and find a way to write heroes, myHero, lastone without using "this"? Similar to how it is done in common JavaScript. https://i.stack.imgur.com/TZ4sM.png ...

Present the Azure OCR results in a systematic order that follows the reading direction

After running a JSON read-script from Azure OCR, I received the following output: # Extracting word bounding boxes and associated text. line_infos = [region["lines"] for region in analysis["regions"]] word_infos = [] for line in line_in ...

The beauty of crafting intricate forms with Angular's reactive nested

In my Angular project, I am exploring the concept of nesting multiple reactive forms within different components. For instance, I have a component called NameDescComponent that includes a form with two inputs - one for name and one for description, along ...

`The Art of Curved Arrows in sigjma.js, typescript, and npm`

I have encountered an issue while trying to draw curved arrows in sigma.js within my TypeScript npm project. The error occurs on the browser/client-side: Uncaught TypeError: Cannot read properties of undefined (reading 'process') at Sigma.pro ...

Using Node.js to inject dependencies into the app.js file

As I work on my node.js and typescript application, I followed the approach outlined in an article by Brian Love. You can find a sample code for the server.ts file below: import * as bodyParser from "body-parser"; import * as cookieParser from "cookie-par ...

Encountering [Object Object] within an angular2 app

https://i.stack.imgur.com/iceKH.pngI recently created an angular2 application using ngrx/effects for handling http calls. My reference point was an application on GitHub. However, I am facing an issue where the response from the HTTP call is not displaying ...

Tips on injecting configuration into forRoot

Is there a method to inject configuration object into AppModule's forRoot() function? How can I access the configService if there is no constructor within the module? config.yml: smtp: host: 'smtp.host.com' port: 10 secure: true aut ...

The Angular 2 dropdown menu isn't populating because of the sluggish http response

I encountered an issue while trying to populate a dropdown list with data from an HTTP response using an Angular2 service. Below is the method in my service: categories: any; getCategories() { let subscription = this.httpclient .get ...

@vx/enhanced responsiveness with TypeScript

I am currently utilizing the @vx/responsive library in an attempt to retrieve the width of a parent component. Below are snippets from my code: import * as React from 'react' import { inject, observer } from 'mobx-react' import { IGlob ...

How to assign a value to an array within a form in Angular 8

I'm facing an issue with my Angular 8 edit form that utilizes a form array. When I navigate to the page, the form array is not populated with values as expected. Can anyone help me identify and solve this problem? ngOnInit(): void { // Fetc ...

Angular 13 throws NG0301 error message, failing to display the problematic module

Can someone provide assistance? Recently, I upgraded my Angular project from version 11 to version 13: Angular: 13.2.4 ... animations, cdk, common, compiler, compiler-cli, core, forms ... platform-browser, platform-browser-dynamic, router Package ...

Struggling with hashtags and ampersands in Angular when making an HTTP request

Dealing with Special Characters # and & in Angular's http.get() Request URL Take a look at my code first. Angular Service let versionsearch = "&"; let strweeksearch = "%23"; this.http.get(this.apiUrl + 'GetVersionInfo?vehicleVersion=' + v ...

Angular reactive form encountered an issue with an incorrect date being passed

Currently, I am utilizing the PrimeNg calendar module to select a date. Here is the code snippet: <p-calendar formControlName="valid_till" [dateFormat]="'mm/dd/yy'"></p-calendar> Upon selecting a date like 31st J ...

Ways to retrieve the specified data in Javascript in string format

I'm facing an issue where the data I passed from a JavaScript array to a Java servlet and back to JavaScript is showing as "undefined." Check out my JavaScript code below: var buildingNumbers = []; // Let's assume the values of buildingNumbers ...

sending a json request using AngularJS

I am attempting to make an AJAX request with a JSON file, but it is not being parsed correctly. Here is my controller: function troopsController($scope, $routeParams, $http) { $http.get('js/data/troops.json').success(function(data) { ...

Step-by-step guide on extracting JSON data from the eBay API

Seeking assistance from anyone who can help. I am using the getrescommededcategory API for eBay, but I am struggling to retrieve the value of one of the fields. I have tried adjusting the code multiple times, using JSON decode and not using it, but I can& ...

Creating a JSON body using a JavaScript function

I am looking to generate a JSON Body similar to the one shown below, but using a JavaScript function. { "events": [{ "eventNameCode": { "codeValue": "xyz api call" }, "originator": { "associateID": "XYZ", "formattedName": " ...

Tips for effectively displaying a user's update or change

In my moments component, each moment is like a thread or post that users can like or dislike. When a user likes a moment, the momentService is called to retrieve the updated list and refresh the like count of that particular moment. However, updating all ...

Having trouble retrieving data from an API URL in JSON format using the Flutter framework

Attempting to retrieve API JSON data such as id, username, photo, etc., I encountered a problem. When using jsonplaceholder, everything works fine; however, when utilizing my own API, no data is returned. Below is the Flutter code I'm using: import ...

Converting a JSON array into a Java HashMap with Jackson: A step-by-step guide

I would like to use Jackson to convert the JSON array below into a Java HashMap, and then iterate over the values as shown: Desired output format: key Value 1 sql 2 android 3 mvc JSON Sample: enter code here { "menu": [ { ...