Rilcon42
Rilcon42

Reputation: 9765

Angular not parsing JSON into object

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}}

Upvotes: 0

Views: 1169

Answers (2)

Heretic Monkey
Heretic Monkey

Reputation: 12114

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.

Upvotes: 1

Sajeetharan
Sajeetharan

Reputation: 222522

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);

Upvotes: 1

Related Questions