无法使用Rest将值从角度2发送到弹簧控制器

时间:2017-03-09 16:25:50

标签: java angular spring-boot

我正在尝试创建一个CRUD应用程序,对于Select操作一切正常但我无法通过将表单的值发送到spring控制器来创建一个新的Personne 这是我的app-components.ts

        import { personne } from './personne';
    import { StylesCompileResult } from '@angular/compiler';
    import { Component } from '@angular/core';
    import { Http, Response, Headers, RequestOptions } from '@angular/http';
    import { Observable } from 'rxjs';
    import 'rxjs/add/operator/map';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      title = 'ICS DashBoard Project';
      http: Http;
      contacts = [
        'toto',
        'momo',
        'soso'
      ];
      personne: Observable<personne[]>;
      constructor(http: Http) {
        //http.get('http://localhost:8082/personne/all');
        this.http = http;
        this.http.get('http://localhost:8082/personne/all').subscribe((res: Response) => this.personne = res.json());


      }

      addPersonne(nom: string, prenom: string, age: number, dateNaissance) {


        /*
        console.log(nom);
          this.http.post('http://localhost:8086/personne/save', 
              {"prenom": prenom,
              "nom":nom,
              "age":age,
              "dateNaissance":dateNaissance
          }).toPromise(); * 
         */
        /*
            var headers = new Headers({ 'Content-Type': 'application/json' });
            var options = new RequestOptions({ headers: headers });
            var body = JSON.stringify( {
            var1:'test',
            var2:'test2'
            });
            var params='json'+body;
            this.http.post('http://validate.jsontest.com', body, headers).map((res: Response) => res.json());
            console.log("ajoutee");
              */
        // var json=JSON.stringify({var1:'test1',var2:3});
        var params = {

          "prenom": prenom,
          "nom": nom,
          "age": age,
          "dateNaissance": dateNaissance
        }

        let options = new RequestOptions({ headers: headers });
        //var head = new Headers();
        console.log("TOTO");
        // head.append('Content-Type','application/x-www-form-urlencoded');
        /*this.http.post('http://localhost:8082/personne/save',params,{

          headers:head
       }).map(res=> res.json())*/


      var headers = new Headers();
      headers.append('Content-Type', 'application/x-www-form-urlencoded');

      this.http.post('http://localhost:3001/sessions/create', params, {
        headers: headers
        })
        .map(res => res.json())
        .subscribe(


          () => console.log('Authentication Complete')
        );
      }
    /*
    updatePersonne(oldName:string, newName:string){
      console.log("UPDATE");
      this.http.post('http://localhost:8082/personne/update', { "oldName": oldName, "newName": newName });
    }*/
          }

这是我的休息控制器

            package org.sqli.Controller;

        import java.util.List;

        import org.sqli.entities.Personne;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.web.bind.annotation.CrossOrigin;
        import org.springframework.web.bind.annotation.PathVariable;
        import org.springframework.web.bind.annotation.RequestBody;
        import org.springframework.web.bind.annotation.RequestMapping;
        import org.springframework.web.bind.annotation.RequestMethod;
        import org.springframework.web.bind.annotation.RestController;
        import org.sqli.service.PersonneService;

        @RestController
        //@CrossOrigin("*")
        //@CrossOrigin(origins = "http://localhost:4200")
        @RequestMapping(value="/personne")
        public class PersonneRestController {

            @Autowired
            private PersonneService personneService;

            @CrossOrigin
            @RequestMapping(value="/save")
            public Personne savePersonne(@RequestBody Personne p){

                System.out.println("persoone :::"+p.getNom());
                return personneService.savePersonne(p);

            }
        /*  @CrossOrigin
            @RequestMapping(value="/update",method=RequestMethod.POST)
            public Personne updatePersonne(@RequestBody String oldName , String newName){
                List<Personne> lPersonne = listPersonne();
                Personne newPersonne = null;
                for(Personne personne : lPersonne){
                    if(personne.getNom().equals(oldName)){
                        newPersonne = personne;
                        newPersonne.setNom(newName);
                        break;
                    }
                }
                    return personneService.updatePersonne(newPersonne);

            }*/

        /*  @CrossOrigin
            @RequestMapping(value="savep",method=RequestMethod.PUT)
            public Personne savePersonnep(@RequestBody Personne p){

                return personneService.savePersonne(p);
            }*/
            @CrossOrigin
            @RequestMapping(value="/all")
            public List<Personne> listPersonne(){
                return personneService.listPersonne();
            }
            @CrossOrigin
            @RequestMapping(value="/delete/{id}",method=RequestMethod.DELETE)
            public void deletePersonne(@PathVariable Long id){
                System.out.println("Delete bien");
                personneService.deletePersonne(id);

            }




        }

2 个答案:

答案 0 :(得分:0)

使用的网址与控制器的端点不匹配:

 //addPersonne
 this.http.post('http://localhost:port/personne/save', params, {
    headers: headers
    })
    .map(res => res.json())
    .subscribe(


      () => console.log('Authentication Complete')
    );

答案 1 :(得分:0)

您需要添加请求方法

 @PostMapping(value = "/save", consumes = { MediaType.APPLICATION_JSON_UTF8_VALUE })
public Personne savePersonne(@RequestBody Personne p){

                System.out.println("persoone :::"+p.getNom());
                return personneService.savePersonne(p);

            }

并验证服务的post方法中的url(AppComponent / addpersonne)