Angular2调用外部REST服务失败

时间:2016-11-22 17:37:45

标签: spring angular spring-restcontroller

我有一个端点为http://localhost:8080/hero-rest-service/getheroes的REST服务。该服务的回复是

  

[{" ID":100,"名称":"测试1"},{" ID":200,&#34 ;名称":" Test2的"},{" ID" 300"名称":" Test3的"},{&# 34; ID" 400"名称":" TEST4"},{" ID" 500"名称":& #34; TEST5"}]

我试图用Angular2用下面的类

来调用它
import { Injectable }     from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { Hero }           from '../beans/hero';
@Injectable()
export class HeroSearchService {
    constructor(private http: Http) {}
    getHeroes(): Observable<Hero[]> {
        return this.http
            .get(`http://localhost:8080/hero-rest-service/getheroes`)
            .map((r: Response) => r.json().data as Hero[])
            .catch(this._serverError);
    }
    private _serverError(err: any) {
        console.log('Sever error:', err);
        if(err instanceof Response) {
            return Observable.throw(err.json().error || 'backend server error');
        }
        return Observable.throw(err || 'backend server error');
    }
}

但它的失败和控制台错误是

Sever error: 
error: "Collection 'getheroes' not found"
status: 404
statusText: "Not Found"
type: null
url: null

英雄课

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

这是我的Rest Controller

@RestController
public class HeroRestController {

    @RequestMapping("/")
    public String welcome() {
        return "Welcome to Angular2 Heroes Spring REST Service.";
    }

    @ResponseBody
    @RequestMapping("/getheroes")
    @CrossOrigin(origins = "http://localhost:3000")
    public List<Message> getHeroes() {
        System.out.println("Inside getHeroes");
        List<Message> msgs = new ArrayList<>();
        Message msg1 = new Message(100, "Test1");
        Message msg2 = new Message(200, "Test2");
        Message msg3 = new Message(300, "Test3");
        Message msg4 = new Message(400, "Test4");
        Message msg5 = new Message(500, "Test5");
        msgs.add(msg1);
        msgs.add(msg2);
        msgs.add(msg3);
        msgs.add(msg4);
        msgs.add(msg5);
        return msgs;
    }
}

任何人都可以帮助我吗?

0 个答案:

没有答案