首页 > 解决方案 > 使用 http put 将值从 Angular 5 传递到 Java REST API,第 0:-1 行在输入处没有可行的替代方案

问题描述

我面临一个尝试学习网络跟踪数据的完整周期的问题,我将值从 java jersay REST-API 传递到 angular 5,但我想将文本从 angular 传递到后端以执行一些查询并再次返回结果,我对@FormParam 和很多事情感到困惑,

在我的代码下面,

文件-list.service.ts

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';
import { FileList } from './file-list';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map'
save(fileList: FileList): Observable<Response> {

console.log('Saving person ' + JSON.stringify(fileList));
return this.http.put('http://localhost:8080/SWBackend/jaxrs/Person/Save', JSON.stringify(fileList), { headers: this.getHeaders()});}

List.component.html

<form (click)="save()" method="POST" action="http://localhost:8080/SWBackend/jaxrs/Person/Save">
    <p>
        Path : <input type="text" name="pathUrl" />
    </p>
    Press to show the files
    <input type="submit" value="Add User" />
    <input type="hidden" name="_method" value="PUT">
</form>

Java 文件.java

@PUT
@Path("Save")
@Consumes({ "application/xml", "application/json" })
@Produces("application/json")
public Response saveEmp(FilesList pathUrl) {
    System.out.println("Reach Save Emp");
    return Response.ok().header("Access-Control-Allow-Origin", "*").build();
}

我收到此错误:

第 0:-1 行在输入 '' 处没有可行的替代方案

我不知道我的方法是否正确,但我从一周前开始尝试,

谢谢你们。

标签: javajerseyangular5

解决方案


试试这个,

在您的表格中删除:

<form (click)="save()" method="POST" action="http://localhost:8080/SWBackend/jaxrs/Person/Save">

使用 FormGroup 和 FormControl 为您的表单使用 ReactiveFormsModule。

然后在您的组件中,当您提交表单时,它将调用该函数来调用您的服务,该服务将与您的 java 控制器进行通信。

组件应具有与模板(html)中的 formGroup 关联的功能。

然后该函数应调用您的服务,例如: this.service.save(fileList);

https://angular.io/guide/reactive-forms

前任:

<form [formGroup]="fileListForm" (ngSubmit)="save(fileListForm.value)">
    <input type="text" formControlName="fileListNameControl">
</form>

零件:

private fileListForm: FormGroup;
private fileListNameControl: FormControl;

 ngOninit(){
   this.fileListForm = new FormGroup({
    fileListNameControl: new FormControl("", Validators.required)
   });
 }



save(form: any){
 // get your form values here and then call service
  this.fileLIstService.save('your value');
}

** 确保通过模块中的 @angular/forms 导入 ReactiveFormsModule。


推荐阅读