0

Can someone explain why my JSON object isnt being correctly parsed into an Angular object? (the Angular object values are empty when I display HTML)

Angular code making request for JSON

GetMessageSub(): void {
  this.http.get('http://localhost:61460/api/values')
    .pipe(map(res => JSON.parse(res.toString())),
        catchError(this.handleError('getMessageSub()', [])))
    .subscribe(people => this.people = people);
}

C# code that is replying with a JSON

public JsonResult Get()
{
    return Json("[{ id:1, name:\"value2\" }]");
}

Angular code that declares a People object

export class People {
    id: number;
    name: string;
  }

HTML that calls the people object (which is populated by GetMessageSub()

people found:  {{people.id}} -- {{people.name}}
2
  • JSON stands for JavaScript Object Notation, so it’s already a object. There is no need to convert it Commented Jul 30, 2018 at 16:14
  • @SandipNirmal Not quite. JSON is a format for a string. Something must parse it to get it into an object. Angular does that automatically in most cases, but it's not because JSON is an object. Commented Jul 30, 2018 at 16:20

2 Answers 2

1

Your C# code:

return Json("[{ id:1, name:\"value2\" }]");

returns a string, "[{ id:1, name:\"value2\" }]", encoded as JSON, so "\"[{ id:1, name:\\\"value2\\\" }]\"", not an array with a single object. If you want to do that, either:

Build an array of objects in C# and send that through JSON:

return Json(new object[] { new { id = 1, name = "value2" } });

Or send it as a string using a ContentResult:

return Content("[{ id:1, name:\"value2\" }]", "application/json");

You'd need to change the signature of your method as well for the latter option.

Sign up to request clarification or add additional context in comments.

2 Comments

I tried having c# return an array of objects like you suggested, but my HTML output was odd: people found: function People() { }:: -- People. I included the HTML call above that generated the output in my post
Note a couple of things: Angular allows you to use res.json() to get the object parsed from the JSON (so, map(res => res.json())). Also, people is going to be an array. Arrays generally don't have id or name attributes. You'll likely need an *ngFor to iterate through the items in the array.
1

You are already returning a valid JSON, no need to parse, just assign

this.http.get('http://localhost:61460/api/values')
    .pipe(map(res =>res)),
        catchError(this.handleError('getMessageSub()', [])))
    .subscribe(people => this.people = people);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.