I would like to turn a json string array into an object array. In this case I have a string receiving from backend
[{"id_pk":3,"heroname":"myherooo"},{"id_pk":12,"heroname":"Narco"}]
and I would like to turn this string into a Hero array and then return it.
My current code:
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => {
console.log(response);
let heroes: Hero[];
let jo = response.text(); // [{"id_pk":3,"heroname":"myherooo"},{"id_pk":12,"heroname":"Narco"}]
console.log("jo: "+jo);
for(let i=0;i<jo.length;i++){
console.log("ele: "+JSON.parse(response.text()[i])); // SyntaxError: Unexpected end of JSON input
heroes[i] = JSON.parse(response.text()[i]);
}
heroes;
})
.catch(this.handleError);
}
Can anybody help?
Update:
This is the solution:
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.map (t=>t.json())
.toPromise()
.then(response => response.map(i => new Hero(i.id_pk, i.heroname)))
.catch(this.handleError);
}