无法将Angular2前端与Springboot JAX-RS后端连接

时间:2018-06-21 09:06:02

标签: angular jax-rs

我在使用Springboot和JAX-RS的CRUD操作将Angular 2前端与后端连接时遇到问题。我添加了JerseyConfig和CORS过滤器,但仍然无法正常工作。

我的后端控制器外观:

@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "users")
@Path("/api")
public class NoteController {


private static Map<Integer, Note> DB = new HashMap<>();     

@GET
@Path("/users")
@Produces("application/json")
public Users getUsers() {
    Users users = new Users();
    users.setUsers(new ArrayList<>(DB.values()));
    return users;
}

@GET
@Path("/user/{id}")
@Produces("application/json")
public Response getUser(@PathParam("id") int id) throws 
URISyntaxException 
{
    Note user = DB.get(id);
    if(user == null) {
        return Response.status(404).build();
    }
    return Response
            .status(200)
            .entity(user)
            .contentLocation(new URI("/user-management/"+id)).build();
}

@DELETE
@Path("/user/{id}")
public Response deleteUser(@PathParam("id") int id) throws 
URISyntaxException {
    Note user = DB.get(id);
    if(user != null) {
        DB.remove(user.getId());
        return Response.status(200).build();
    }
    return Response.status(404).build();
}

@PUT
@Path("/user")
@Consumes("application/json")
@Produces("application/json")
public Response updateUser(@PathParam("id") int id, Note user) throws 
URISyntaxException 
{
    Note temp = DB.get(id);
    if(user == null) {
        return Response.status(404).build();
    }
    temp.setFname(user.getFname());
    temp.setLname(user.getLname());
    DB.put(temp.getId(), temp);
    return Response.status(200).entity(temp).build();
}

@POST
@Path("/user")
@Consumes("application/json")
public Response createUser(Note user) throws URISyntaxException 
{
    if(user.getFname() == null || user.getLname() == null) {
        return Response.status(400).entity("Please provide all mandatory 
     inputs").build();
    }
    user.setId(DB.values().size()+1);
    user.setUri("/user-management/"+user.getId());
    DB.put(user.getId(), user);
    return Response.status(201).contentLocation(new 
    URI(user.getUri())).build();
}

static
{
    Note user1 = new Note();
    user1.setId(1);
    user1.setFname("John");
    user1.setLname("Wick");
    user1.setUri("/user-management/1");

    Note user2 = new Note();
    user2.setId(2);
    user2.setFname("Harry");
    user2.setLname("Potter");
    user2.setUri("/user-management/2");

    DB.put(user1.getId(), user1);
    DB.put(user2.getId(), user2);
}

}

我想在Angular中导入代码是:

import { Injectable } from '@angular/core';
import{Http, Response, Headers, RequestOptions} from '@angular/http';
import { Observable}   from 'rxjs/Observable';
import { map} from 'rxjs/operators';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import{User}  from '../user';


@Injectable({
providedIn: 'root'
})

export class UserService {
private baseUrl:string='http://localhost:8080/api';
private headers = new Headers({'Content-Type':'application/json'});
private options = new RequestOptions({headers:this.headers});
private user = new User();
constructor(private _http:Http) { }

getUsers(){
return this._http.get(this.baseUrl+'/users',this.options)
  .map((response:Response)=>response.json())
  .catch(this.errorHandler);
 }

  getUser(id:Number){
  return this._http.get(this.baseUrl+'/user/'+id,this.options)
  .map((response:Response)=>response.json())
  .catch(this.errorHandler);
 }

 deleteUser(id:Number){
 return 
 this._http.delete(this.baseUrl+'/user/'+id,this.options)
 .map((response:Response)=>response.json())
 .catch(this.errorHandler);
 }


createUser(user:User){
return this._http.post(this.baseUrl+'/user',JSON.stringify(user),  
this.options).map((response:Response)=>response.json())
  .catch(this.errorHandler);
}

updateUser(user:User){
return this._http.put(this.baseUrl+'/user',JSON.stringify(user),  
this.options).map((response:Response)=>response.json())
  .catch(this.errorHandler);
}

errorHandler(error:Response){
return Observable.throw(error||"SERVER ERROR");
}

setter(user:User){
 this.user=user;
}

getter(){
return this.user;
}

}

使用DevTool查看错误Massage是:

ERROR Error: Cannot find a differ supporting object '[object Object]'of 
type 'object'. 
NgFor only supports binding to Iterables such as Arrays.
at NgForOf.push../node_modules/@angular/common/
fesm5/common.js.NgForOf.ngOnChanges (common.js:3379)
at checkAndUpdateDirectiveInline (core.js:10093)
at checkAndUpdateNodeInline (core.js:11363)
at checkAndUpdateNode (core.js:11325)
at debugCheckAndUpdateNode (core.js:11962)
at debugCheckDirectivesFn (core.js:11922)
at Object.eval [as updateDirectives] (ListuserComponent.html:12)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:11914)
at checkAndUpdateView (core.js:11307)
at callViewAction (core.js:11548)
View_ListuserComponent_0 @ ListuserComponent.html:12 

我想这个问题在此类中的某个地方:

 import { Component, OnInit } from '@angular/core';
 import{UserService}  from '../../shared_service/user.service';
 import{User}  from '../../user';
 import{Router}  from '@angular/router';

 @Component({
  selector: 'app-listuser',
  templateUrl: './listuser.component.html',
  styleUrls: ['./listuser.component.css']
  })
  export class ListuserComponent implements OnInit {
  private users:User[];
  constructor(private _userService:UserService, 
  private _router:Router) { }

  ngOnInit() {

  this._userService.getUsers().subscribe(user=>{
    { this.users = user};
  },(error)=>{
    console.log(error);
  })
  }

deleteUser(user){
this._userService.deleteUser(user.id).subscribe((data)=>{
    this.users.splice(this.users.indexOf(user),1);
},(error)=>{
  console.log(error);
});
}

  updateUser(user){  
  this._userService.setter(user);
  this._router.navigate(['/op']);


  } 
  newUser(){
  let user = new User();
  this._userService.setter(user);
 this._router.navigate(['/op']);

 } 

 }

我在localhost:8080 / api / users /上看到我的后端工作正常,但是在localhost:4200上的前端中却没有显示我的数据。有人知道问题出在哪里,能为我提供帮助吗?

1 个答案:

答案 0 :(得分:-1)

尝试使用:

@CrossOrigin

您的Controller类上的注释,例如;

@XmlAccessorType(XmlAccessType.NONE)
...
@CrossOrigin
public class NoteController {
...

或者在每个入口点上,例如:

@CrossOrigin
...
public Response deleteUser(@PathParam("id") int id) throws 
...