我试图从后端使用Sring MVC,Rest并添加CORS(Cross-origin-resourc-sharing)来获取英雄列表。
JSON响应:
[{"id":1,"name":"Sai"},{"id":2,"name":"Ram"},{"id":11,"name":"Mr. Nice"},{"id":12,"name":"Narco"},{"id":13,"name":"Bombasto"},{"id":14,"name":"Celeritas"},{"id":15,"name":"Magneta"},{"id":16,"name":"RubberMan"},{"id":17,"name":"Dynama"},{"id":18,"name":"Dr IQ"},{"id":19,"name":"Magma"},{"id":20,"name":"Tornado"}]
因此,当我尝试从邮递员和浏览器中获取该URL时,我正在收回JSON,但是当我在我的前端代码中使用时,它没有给我这些对象
在前端我使用的是角度2框架。所以这是我如何实现代码,请让我知道这个问题是什么?
英雄服务:
export class HeroService {
private heroUrl: string = "http://localhost:7001/springmvcrestfulwebservice/service/heroes/";
constructor(private http:Http){
}
getHeroes(): Promise<Hero[]>{
//return Promise.resolve(HEROES);
return this.http.get(this.heroUrl)
.toPromise()
.then(response=>response.json().data as Hero[])
.catch(this.handleError);
}
}
HeroesComponent:
import {Component, OnInit} from '@angular/core';
import {HeroService} from './hero.service';
import {Hero} from "./Hero";
@Component({
moduleId: module.id,
providers: [HeroService],
selector: 'heroes',
templateUrl: 'heroes.component.html'
})
export class HeroesComponent implements OnInit{
myHeroes: Hero[];
constructor(private heroService: HeroService){}
ngOnInit(){
this.getDataFromServer();
}
getDataFromServer():void{
this.heroService.getHeroes()
.then(
myHeroes => this.myHeroes = myHeroes
);
}
}
myHeroes中没有任何内容出现。请帮帮我。
答案 0 :(得分:0)
如果您重写服务以返回Observable并转换为Component中的Promise,那么get call是否会出现在网络标签中?
//Hero Service
getHeroes(): Observable<Hero[]>{
return this.http.get(this.heroUrl)
.map(response => response.json() as Hero[])
.catch(this.handleError);
}
//Hero Component
this.heroService.getHeroes()
.toPromise()
.then(
myHeroes => this.myHeroes = myHeroes
);