将JSON字符串转换为Angular CLI中的对象数组

忍者石

我想将json字符串数组转换为对象数组。在这种情况下,我有一个从后端接收的字符串

[{"id_pk":3,"heroname":"myherooo"},{"id_pk":12,"heroname":"Narco"}]

我想将此字符串转换为Hero数组,然后将其返回。

我当前的代码:

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

有人可以帮忙吗?

更新:

这是解决方案:

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);
   }
像素位

用途map(t=> t.json())

return this.http.get(this.heroesUrl)
        .map (t=>t.json())
        .toPromise()
        ...

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章