【问题标题】:angular 2 get data from rest server is zero length - how to debug?角度 2 从休息服务器获取数据的长度为零 - 如何调试?
【发布时间】:2016-09-28 22:53:22
【问题描述】:

使用 Angular 2 网站上的英雄教程。我已经将 heroService 设置为使用来自 tomcat 的休息服务。使用 curl 会产生正确的结果

C:\Temp\curl>curl http://centos7-ansible:8080/heroes/heroes
[{"id":1,"name":"Mr. Nice"},{"id":2,"name":"Narco"},{"id":3,"name":"Bombasto"},{"id":4,"name":"Celeritas"},{"id":5,"name":"Magneta"},{"id":6,"name":"RubberMan"},{"id":7,"name":"Dynama"},{"id":8,"name":"Dr IQ"},{"id":9,"name":"Magma"},{"id":10,"name":"Tornado"}]

所以在 hero.service.ts 中,

private heroesUrl = 'http://centos7-ansible:8080/heroes/heroes';  // URL to web api
getHeroes(): Promise<Hero[]> {
        return this.http.get(this.heroesUrl)
               .toPromise()
               .then(response => response.json().data as Hero[])
               .catch(this.handleError);
    }

在调用组件中,

  ngOnInit(): void {
        console.log("about to get data");   
    this.heroService.getHeroes().then(heroes => this.heroes = heroes.slice(4, 8));
        console.log("returned from getting data");
        console.log(length of array is " + this.heroes.length );
  }

看着我得到的控制台

about to get data 
GET http://centos7-ansible:8080/heroes/heroes   200 OK  43ms     
returned from getting data 
length of array is 0

所以它可以在 curl 中工作,但在 Angular 中却不行。

另外,查看 Tomcat 中的访问日志,相同的日志消息适用于 curl 和 Angular 访问。

"GET /heroes/heroes HTTP/1.1" 200 273
"GET /heroes/heroes HTTP/1.1" 200 273

“273”是返回数据的长度吗?这表明数据存在但未放入 Hero 数组中? 我的 herosUrl 正确吗? 在控制台中,我得到

EXCEPTION: Uncaught (in promise): TypeError: e is undefined

这是什么意思?什么是“e”? 当控制台将代码行作为 bundle.js 的一部分提供时,我该如何进行调试。

【问题讨论】:

  • 您的 json 中没有 data
  • 这是因为我从使用 inMemoryDbService 切换到使用外部服务的原因吗?

标签: angular


【解决方案1】:

你能不能把下面这行替换掉

    this.heroService.getHeroes().then(heroes => this.heroes = heroes.slice(4, 8));

    this.heroService.getHeroes().then(heroes => { this.heroes = heroes.slice(4, 8);  console.log(length of array is " + this.heroes.length ); });

并检查现在控制台中是否打印了正确的长度?

【讨论】:

  • Kevin,按照您的建议进行了更改。日志消息不会出现在控制台中。显示 getHeroes() 调用之前的日志消息,但不显示数组长度。由于网页没有显示任何数据,我认为数组长度为零是正确的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-28
相关资源
最近更新 更多