【问题标题】:POST List<object> from Angular2 Service to SpringBoot RestControllerPOST List<object> 从 Angular 2 服务到 Spring Boot RestController
【发布时间】:2018-02-03 08:38:49
【问题描述】:

enter image description hereHi我实际上是在Angular2(前端)和Springboot(后端)中制作一个应用程序。 到目前为止,我已经从 angular2 向 Springboot 发出了许多请求,即 GET ;POST 。我什至将单个 Json 对象从 Angular2 服务发送到 Springboot。

但目前我有一个场景,我需要将 Json 对象列表从 Angular2 发送到 Springboot Rest 控制器。但不幸的是我无法做到这一点。

我正在做的是

1:我创建了一个类型数组,我需要在 angular2 中发送对象。 2:将同一 txpe 的单个 json 对象推入该数组 3.在函数调用中将该数组传递给 angular2 的服务。 4.终于向Springboot Controller发起了POST请求

下面是我将 JSon 对象添加到数组的函数:

updateChecked(value, event) {
    // console.log(event.target.getAttribute('value'));

    if (event.target.checked) {
        // this.checkArr.push(event.target.getAttribute('value'));
        this.checkArr.push({
            profil_id: event.target.getAttribute('value'),
            profil_name_lang: null,
            profil_name_short: null,
            geschaeftsbereich: null,
            spezialberatung: null
        });
    } else if (!event.target.checked) {
        //let indexx = this.checkArr.indexOf(event.target.getAttribute('value'));
        let indexx = this.checkArr.findIndex(_profile => _profile.profil_id === event.target.getAttribute('value'));
        this.checkArr.splice(indexx, 1);
        console.log(indexx);
    }
}

下面是我的Angular2服务函数

private _deleteURL = 'http://localhost:9000//deleteprofile'
private headers1 = new Headers({'Content-Type' : 'application/x-www-form-urlencoded'});

deleteProfile(chckArr: Profile[]): Promise < Profile > {
    // console.log("karan in delete");
    console.log(chckArr);
    return this.http
        .post(this._deleteURL, chckArr, {
            headers: this.headers1
        })
        .toPromise()
        .then(res => res.json().data as Profile)
        .catch(this.handleError);
}

下面是我的 Springboot 功能:-

@RequestMapping(method = RequestMethod.POST, value = "/deleteprofile")
 public void deleteProfile(@RequestBody List < Profile > profile) { // function to delete an existing profiles 

     try {
         //     profileservice.deleteProfile(profile);
     } catch (Exception e) {
         e.printStackTrace();
     }
 }

Angular2 中的实体类

export class Profile {
    profil_id: string;
    profil_name_lang: string;
    profil_name_short: string;
    geschaeftsbereich: string;
    spezialberatung: string;
}

Springboot 中的实体类

package permissionbackendservice.permissionmatrix.domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonIgnore;


@Entity
//@IdClass(ActivityId.class)
@Table(name = "T_DM_VM_PROFILE_DIM")

public class Profile implements Serializable {


    /**
     * 
     */
    private static final long serialVersionUID = 1 L;


    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "PROFIL_ID")
    private String profil_id = null;


    @Column(name = "PROFIL_NAME_LANG")
    private String profil_name_lang = null;

    @Column(name = "PROFIL_NAME_KURZ")
    private String profil_name_short = null;

    @Column(name = "GESCHAEFTSBEREICH")
    private String geschaeftsbereich = null;

    @Column(name = "SPEZIALBERATUNG")
    private String spezialberatung = null;




    public String getProfil_id() {
        return profil_id;
    }

    public void setProfil_id(String profil_id) {
        this.profil_id = profil_id;
    }

    public String getProfil_name_lang() {
        return profil_name_lang;
    }

    public void setProfil_name_lang(String profil_name_lang) {
        this.profil_name_lang = profil_name_lang;
    }

    public String getProfil_name_short() {
        return profil_name_short;
    }

    public void setProfil_name_short(String profil_name_short) {
        this.profil_name_short = profil_name_short;
    }

    public String getGeschaeftsbereich() {
        return geschaeftsbereich;
    }

    public void setGeschaeftsbereich(String geschaeftsbereich) {
        this.geschaeftsbereich = geschaeftsbereich;
    }

    public String getSpezialberatung() {
        return spezialberatung;
    }

    public void setSpezialberatung(String spezialberatung) {
        this.spezialberatung = spezialberatung;
    }
}

错误:

【问题讨论】:

  • 你也发布后端日志吗?
  • 后端没有产生任何错误或消息,,, 刚刚调用springboot来了
  • 任何人都可以帮忙

标签: json angular post spring-boot angular2-services


【解决方案1】:

使用 @RequestBody 的数组更改您的控制器 deleteProfile() 方法,如下所示:

@RequestMapping(method = RequestMethod.POST, value = "/deleteprofile")
 public void deleteProfile(@RequestBody Profile[] profile) { 
 // function to delete an existing profiles 

     try {
         //     profileservice.deleteProfile(profile);
     } catch (Exception e) {
         e.printStackTrace();
     }
 }

如果 profileservice.deleteProfile() 需要配置文件列表而不是数组,您可以使用 Arrays.asList(profile)

获取它

在客户端,您必须发送 application/json 请求。因此,通过删除标头来更新您的客户端请求:

private _deleteURL = 'http://localhost:9000/deleteprofile'

deleteProfile(chckArr: Profile[]): Promise < Profile > {
    // console.log("karan in delete");
    console.log(chckArr);
    return this.http
        .post(this._deleteURL, chckArr)
        .toPromise()
        .then(res => res.json().data as Profile)
        .catch(this.handleError);
}

这不是问题,但您也忘记了在您的网址中尾随“/”。

UPDATE WITH WORKING CODE

Person 微服务中的 Rest 控制器:

@RestController
@RequestMapping("/api")
public class CustomController {
    private static Logger log = LoggerFactory.getLogger(CustomController.class);

    @Autowired
    PersonService personService;

    @RequestMapping(method = RequestMethod.POST, value = "/deleteperson")
    public ResponseEntity deletePerson(@RequestBody Person[] persons) {
        log.info(" Batch delete " + persons);
        personService.delete(Arrays.asList(persons));
        return ResponseEntity.ok().build();
    }

}

网关中的 Angular 服务:

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import {Person} from './person.model';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class CustomService {
    constructor(private http: Http) {

    }

    batchDelete(persons: Person[]): Observable<any> {
        return this.http.post('/person/api/deleteperson', persons);
    }

}

删除方法int person.component.ts:

batchDelete() {
    console.log('--- delete ---- ' + JSON.stringify(this.people));
    this.customService.batchDelete(this.people).subscribe( (res) => {
        this.eventManager.broadcast({ name: 'personListModification', content: 'Delete them all'});

    });
}

CODE ON GITHUB

结果: 前

删除后

【讨论】:

  • 感谢伙伴尝试了您的解决方案,但是,我在浏览器控制台上遇到另一个错误:-状态:415:“url 编码”不支持,“路径”:“//deleteprofile”。我还添加了一个屏幕截图。请看一下并提出一些建议
  • 当使用 application/json 发送时,它在浏览器控制台上给了我错误 --> json 意外结束。我猜它期待单个 json ,,,当我发送 json 数组时,它不能处理它
  • 也试过这个,它说 JSon 输入意外结束,也许它只需要一个 json
  • 是的,您必须发送一个 json 数组,就像您实际设置的 Angular 客户端一样,因为您的 Spring 方法 deleteProfile(@RequestBody Profile[] profile) 需要一个 Profile 数组。如果还是不行,有时间我会在github上发一个示例代码。
  • 但我正在发送 json 数组,我没有发送单个 json。它仍然有效 ,,,,我的数据结构就像 [{} , {}] - 正在发送两个 jsons
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-09
  • 2015-11-06
  • 2015-07-04
  • 2017-04-20
  • 2017-02-09
  • 2019-05-11
  • 2018-01-30
相关资源
最近更新 更多