在angular2中获取json并将其转换为数组

Obtaining json and convert it to array in angular2

本文关键字:转换 数组 angular2 获取 json      更新时间:2023-09-26

为了熟悉它,我做了angular网站上的angular2快速入门和英雄指南教程,在它运行之后,我觉得下一步是使用nodejskoa在英雄指南应用程序中添加一个数据库连接,以增加一点可扩展性。我遵循https://github.com/mahalo1984/TourOfHeroesWithMongoDb本教程的大部分内容,将数据库从mongo更改为mysql,并根据需要进行调整。

我已经把我的代码上传到https://github.com/nagarz/HeroEditor给那些想看所有代码的人。

我已经得到了数据库设置工作,我得到json格式的查询结果,但当我试图拿起它与getHeroes服务应该转换发送一个承诺到模板,我得到这个

EXCEPTION: Uncaught (in promise): TypeError: Cannot read property 'slice' of undefined

我对JS有点陌生,我得到了它的大部分,我能够修复给定日志的错误,但这个是我无法过去的东西,这个。我不是JS/angular2向导,但从我得到的json没有被服务正确地挑选,当它试图将其转换为数组并将其切片以从中获得X个元素时,它会给出错误。我尝试了不同的方法来让它工作,但没有成功,所以我想我应该在这里问,希望有人比我更优秀(不是那么难,感觉不好)可以看到问题所在,并指出我的问题,这样我就可以完成整个设置。

这是我用来查询数据库的路由

router.get('/api/heroes', function* (){ var rows = yield db.query("select * from heroes"); this.body = { heroes: rows }; });

当我在浏览器中输入url http://localhost:3333/api/heroes时,我得到json中的结果,如下所示

{"heroes":[{"id":1,"hid":1,"name":"Saitama"},{"id":2,"hid":2,"name":"Genos"},{"id":3,"hid":3,"name":"Watchdog Man"},{"id":4,"hid":4,"name":"Metal BAt"},{"id":5,"hid":5,"name":"Puri Puri Prisoner"},{"id":6,"hid":10,"name":"Speed of sound, Sonic"},{"id":7,"hid":11,"name":"Tatsumaki"}]}

这就是我获得响应的地方,并尝试将其转换为一个数组来处理应用程序中的信息。

@Injectable()
export class HeroService {
    private headers = new Headers({'Content-Type': 'application/json'});
    ...
    private getHeroesUrl = 'http://localhost:3333/api/heroes';
    constructor(private http: Http) {}
    //this is the method in question
    getHeroes(): Promise<Hero[]> {
        return this.http.get(this.getHeroesUrl).toPromise().then(response => response.json().data as Hero[]).catch(this.handleError);
    }
}

这是Hero模型类:

export class Hero {
    hid: number;
    name: string;
}

这是调用服务方法的类,获得的数组被切片,以及我获得异常的点

export class DashboardComponent implements OnInit {
    heroes: Hero[] = [];
    ...
    ngOnInit(): void {
        this.heroService.getHeroes().then(heroes => this.heroes = heroes.slice(1, 4));
    }
    ...

}

这是异常的完整堆栈跟踪:

Unhandled Promise rejection: Cannot read property 'slice' of undefined ; Zone: angular ; Task: Promise.then ; Value: TypeError: Cannot read property 'slice' of undefined at eval (http://localhost:3000/app/components/dashboard.component.js:22:91) at ZoneDelegate.invoke (http://localhost:3000/node_modules/zone.js/dist/zone.js:203:28) at Object.onInvoke (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:6242:41) at ZoneDelegate.invoke (http://localhost:3000/node_modules/zone.js/dist/zone.js:202:34) at Zone.run (http://localhost:3000/node_modules/zone.js/dist/zone.js:96:43) at http://localhost:3000/node_modules/zone.js/dist/zone.js:462:57 at ZoneDelegate.invokeTask (http://localhost:3000/node_modules/zone.js/dist/zone.js:236:37) at Object.onInvokeTask (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:6233:41) at ZoneDelegate.invokeTask (http://localhost:3000/node_modules/zone.js/dist/zone.js:235:42) at Zone.runTask (http://localhost:3000/node_modules/zone.js/dist/zone.js:136:47) TypeError: Cannot read property 'slice' of undefined at eval (http://localhost:3000/app/components/dashboard.component.js:22:91) at ZoneDelegate.invoke (http://localhost:3000/node_modules/zone.js/dist/zone.js:203:28) at Object.onInvoke (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:6242:41) at ZoneDelegate.invoke (http://localhost:3000/node_modules/zone.js/dist/zone.js:202:34) at Zone.run (http://localhost:3000/node_modules/zone.js/dist/zone.js:96:43) at http://localhost:3000/node_modules/zone.js/dist/zone.js:462:57 at ZoneDelegate.invokeTask (http://localhost:3000/node_modules/zone.js/dist/zone.js:236:37) at Object.onInvokeTask (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:6233:41) at ZoneDelegate.invokeTask (http://localhost:3000/node_modules/zone.js/dist/zone.js:235:42) at Zone.runTask (http://localhost:3000/node_modules/zone.js/dist/zone.js:136:47)

in-memory-web-api模块有一个突破性的变化:

从v0.5.0(2017年10月5日)开始,数据封装配置默认值从false更改为true。HTTP响应体包含直接使用数据值,而不是封装这些值的对象值,{data:…}。这是一个影响几乎所有人的突破性变化现有的应用!

那么,在这个例子中,修改这个:

  getHeroes(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl)
      .toPromise()
      .then(response => response.json().data as Hero[])
      .catch(this.handleError);
  }

:

  getHeroes(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl)
      .toPromise()
      .then(response => response.json() as Hero[])
      .catch(this.handleError);
  }

看起来您希望返回一个数组,但数据实际上是一个对象。试试这个

getHeroes(): Promise<Hero[]> {
  return this.http.get(this.getHeroesUrl).toPromise().then(response => response.json().data.heroes as Hero[]).catch(this.handleError);
}

你的英雄数组嵌套在JSON数据结构中的'heroes'键下。