Trouble with parsing JSON in rxjs ajax response

Currently, I am facing an issue while parsing a JSON string within an ajax callback in Angular2.
After executing response.json()) and using console.log(), everything seems to be functioning correctly.

This is the specific JSON data that I am attempting to parse:

{
  "success": true,
  "data": {
    "id": "14cf4717-f5b6-4002-96b2-321324fc4077",
    "number": "1234",
    "sections": [
      {
        "id": "53f43dd7-4c93-4925-a51d-c6f81f314275",
        "description": "Test",
        "created_at": "2017-10-07 15:08:01",
        "updated_at": "2017-10-07 15:08:01",
        "lines": [
          {
            "id": "73fab07f-4401-43a4-99a4-13c891907ea7",
            "product_id": "62aa5388-712d-4ab1-9e64-6849889194d1",
            "product_name": "Product",
            "product_description": "test",
            "product_type": "product",
            "quantity": "1.00",
            "product": {
              "id": "62aa5388-712d-4ab1-9e64-6849889194d1",
              "name": "Product",
              "description": "test"
            }
          }
        ]
      }
    ],
    "notes": []
  }
}

Within this method:

 public getQuotation(quotationId: string, callback: Function) {
    this.http.get('/quotation/' + quotationId).subscribe((response) => {

      const responseJson = response.json();
      console.log(responseJson);

      callback(null);
    }, () => {
      callback(null);
    });
  }

The outcome is as expected: https://i.sstatic.net/kJt7c.png

However, when I insert this line below the console.log():

const quotation = <FinBaseModel>(responseJson.data);

public getQuotation(quotationId: string, callback: Function) {
    this.http.get('/quotation/' + quotationId).subscribe((response) => {

      const responseJson = response.json();
      console.log(responseJson);

       const quotation = <FinBaseModel>(responseJson.data);

      callback(quotation);
    }, () => {
      callback(null);
    });
  }

It results in the lines array being empty...

https://i.sstatic.net/88rtJ.png

I am puzzled by how this can happen since I perform the console.log() before trying to cast it to a FinBaseModel

If anyone has any insights on why this occurs and how I could resolve it, please share.

Answer №1

Try an alternative approach by avoiding the use of JSON.parse:

this.http.get('/quote/' + quoteId)
    .map(response=> response.json())
    .subscribe((responseData) => {
         console.log(responseData);
    });

Answer №2

When console.log is used, it prints the object by reference. The object may have been mutated before the printing occurs, perhaps due to a callback function.

console.log(responseJson.data) 
const result = <CustomModel>(responseJson.data);
callback(result);

Answer №3

Based on the information you have shared, I may not be able to provide a direct solution at this time. However, I can assist you in properly debugging your code: To accurately examine the values and determine if they are being changed when logged, it is recommended to log a clone of the data instead. Update your console.log(response.data) with

console.log(JSON.parse(JSON.stringify(response.data)))
. Make this adjustment for both logs and compare the output. This method should help you identify whether the value is actually being modified within your callbacks. Keep in mind that TypeScript types serve as a tool for type safety and precision without affecting the actual behavior of your code.

Answer №4

Utilize the HttpClient module. Explore Documentation
Here is an example:

http.get<ItemsResponse>('/api/items').subscribe(data => {
// The data now represents ItemsResponse type, allowing you to access:
   this.results = data.results;
});


 getQuotation(quotationId: string, callback: Function) {
    this.http.get<FinBaseModel>('/quotation/' + quotationId).subscribe((data) => {

 // You can invoke your callback here and provide 'data'
 // callback(data)
 // Alternatively, simply return the value and utilize it without needing to convert to JSON
    return data
}

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

My goal is to create a comprehensive collection of stories showcasing all Material UI components in React

Looking for a way to efficiently import all MUI components stories into my storybook. Is there a tool or repository available that can automate the generation of these stories, or perhaps has pre-written stories for all MUI components? I attempted to cre ...

Leveraging a template variable that stores a JSON object within the Postman Collection Runner

I'm struggling to utilize the Postman collection runner for posting multiple objects to an API from a JSON file structured somewhat like this: [ { "id": "170", "body": { "name": "prod1", "category": "catego ...

Bug in timezone calculation on Internet Explorer 11

I've spent hours researching the issue but haven't been able to find any effective workarounds or solutions. In our Angular 7+ application, we are using a timezone interceptor that is defined as follows: import { HttpInterceptor, HttpRequest, H ...

What might be causing the 500 internal error in jquery.min?

Hello, I am encountering a 500 internal server error when I click this button that performs the following action: $(".btn-email").on('click', function() { swal('Waiting','Please wait, sending email now','info'); ...

Leveraging jest for handling glob imports in files

My setup involves using webpack along with the webpack-import-glob-loader to import files utilizing a glob pattern. In one of my files (src/store/resources/module.ts), I have the following line: import '../../modules/resources/providers/**/*.resource. ...

Combining cells for certain entries in an Angular data table

Just starting to learn angular, and here's the scenario I'm dealing with: I have a table consisting of 10 columns. Let's say column 4 contains different status categories like children, teen, young, adult, and senior. When displaying all ...

Invoke Observable.subscribe() sequentially

I have an array of objects and need to iterate over each element, making a request to the service for each one. However, I want to ensure that the next iteration only occurs when the current request is successfully completed, or block any further requests. ...

The minimum and maximum validation functions are triggered when I am not utilizing array controls, but they do not seem to work when I use array controls

Take a look at the stack blitz example where min and max validation is triggered: https://stackblitz.com/edit/angular-mat-form-field-icrmfw However, in the following stack blitz with an array of the same controls, the validation does not seem to be worki ...

NGXS: Issue with passing objects to "setState" occurs when any of the patched inner fields is nullable or undefined

In my Angular components, I have created a class that is responsible for storing the state: export class MyStateModel { subState1: SubStateModel1; substate2: SubStateModel2; } This class has simple subclasses: export class SubStateModel1 { someField ...

Converting Umbraco Json to a CSS class named "[]"

I'm currently using Umbraco with the data-type grid layout and I am trying to add custom settings (CSS classes) to each row/cell. The results are somewhat working, but I want to improve it. Here's the user interface: https://i.stack.imgur.com/iY ...

What is the best way to incorporate the same partial multiple times with varying content in Nunjucks?

I'm working on several page templates that require the same partial to be included multiple times but with different content each time. I explored looping this, but the order might not always be sequential. Here's an example of how my page templ ...

Transforming functions into a new typed object with different function signatures

I am currently updating some React/Redux code that previously followed an older pattern to a more modern "hooks" based approach, using TypeScript. In the old pattern, we utilized "class-based" components and passed their "dispatch" functions using mapDisp ...

The CORS preflight request for OPTIONS method is returning a 401 (Unauthorized) response from a Windows Authenticated web API

I am facing an issue with my .NET Web API project that uses Windows Authentication. In my development environment, I am unable to make a successful POST request with data from my Angular app. The error message I receive is: OPTIONS http://localhost:9090/a ...

Halt of dispatcher playback occurs after a duration of 10 minutes with discord.js

Currently, I've been working on a music bot using discord.js. To handle audio streaming, I'm utilizing @discordjs/opus and ytdl-core-discord. Everything runs smoothly when testing the bot locally on my machine - songs from YouTube are played with ...

Issue with the exported elements known as 'StatSyncFn'

My build is showing an error that I'm unable to identify the source or reason for. The error message looks like this... Error: node_modules/webpack-dev-middleware/types/index.d.ts:204:27 - error TS2694: Namespace '"fs"' has no expo ...

The function json.stringify fails to invoke the toJson method on every object nested within the main object

When using IE 11, I encountered an issue where calling Stringify on my objects did not recursively call toJson on all objects in the tree. I have implemented a custom toJson function. Object.prototype.toJSON = function() { if (!(this.constructor.name == ...

The error message you are encountering is: "Error: Unable to find function axios

Can't figure out why I'm encountering this error message: TypeError: axios.get is not functioning properly 4 | 5 | export const getTotalPayout = async (userId: string) => { > 6 | const response = await axios.get(`${endpoint}ge ...

Deciphering Encrypted JSON Data

In need of help with our app that generates complex JSON objects where properties and values are in hexadecimal format. How can we convert them back to strings? Example Object: { "636f756e747279": { "6e616d65": "43616e616461", "6 ...

Unraveling the complexities of parsing multi-tiered JSON structures

I am struggling with indexing values from a multi-level JSON array. Here is the JSON data in question: { "items": [ { "snippet": { "title": "YouTube Developers Live: Embedded Web Player Customization" } ...

Submitting MongoDB ObjectIDs using Postman

I am currently using MongoDb.Driver within my C# project, and I have a model structured like this: public class MyClass { [BsonId] public ObjectId Id { get; set; } public ObjectId UserId { get; set; } } The UserId field is of type ObjectId ...