【发布时间】: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