Sean
Sean

Reputation: 398

JSON object from Angular http not deserializing properly

First here are my operating versions: node v12.13.1 | npm 6.12.1

I am having some issues understanding why this isn't de-serializing properly. I am receiving the following back from my rest service.

{ "numbers":[],
  "batches":[ 
    { "id":"AB3E809","status":"1"},
    { "id":"EEF32A9","status":"0"}] }

These are the TypeScript interfaces I am using when trying to type the data.

interface NumJson {
  status: string,
  num: string
}

interface BatchJson {
  id: string,
  status: string
}

interface Status {
  numbers: NumJson[],
  batches: BatchJson[];
}

When making these calls from my Angular service, it doesn't seem to recognize or access the data properly.

this.http.get<any>(url).subscribe({
  next: (data: Status) => {
    console.log(data);              // same as JSON above
    console.log(data.numbers);      // undefined
    console.log(data.batches);      // undefined
}

this.http.get<any>(url).subscribe({
  next: (data: any) => {
    console.log(data);              // same as JSON above
    console.log(data.numbers);      // undefined
    console.log(data.batches);      // undefined
}

Any insights on this would be great as this is the only subscribe that is having issues.

Upvotes: 1

Views: 964

Answers (1)

Sean
Sean

Reputation: 398

I figured out the issue after some thought provoking examples from 'Kurt Hamilton'. My issue was with how the rest service was returning my data.

The correctly formatted data should look like this in the console:

Expected Output

My outputs were displaying strings; which made me question why my data was a string verse an object in the console. (A good note to take away from this issue)

After inspecting the rest service, I realized that it was doing a double serialization. Once I corrected that, the data output looked and acted correctly.

Upvotes: 2

Related Questions