首页 > 解决方案 > 如何将角度 html 表单输入发送到 Spring Boot Rest Web 控制器

问题描述

我正在尝试通过角度前端和弹簧引导休息网络控制器向我的后端发送一个或多个基因的列表

我的html页面:

<div class="container">
  <h1>Clustertool gene(s) input</h1>
  <form (ngSubmit)="onSubmit()" #clusterForm="ngForm">
    <div class="form-group">
      <label for="gene">gene(s) </label>
      <input type="text" class="form-control" id="gene" required>
    </div>
    <button type="submit" class="btn btn-success">Submit</button>
    </form>
</div>

零件

import { Component, OnInit } from '@angular/core';
import { ClustertoolService} from "../../clustertool.service";

@Component({
  selector: 'app-cluster-tool',
  templateUrl: './cluster-tool.component.html',
  styleUrls: ['./cluster-tool.component.css']
})
export class ClusterToolComponent implements OnInit {
  onSubmit() {
    this.clustertoolService.getCell()
  }
  constructor(private clustertoolService: ClustertoolService) { }

  ngOnInit() {
    this.clustertoolService.getCell()
  }
}

服务页面

import { Injectable } from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {Observable} from "rxjs";

@Injectable({
  providedIn: 'root'
})
export class ClustertoolService {
  private clusterUrl: string;

  constructor(private http: HttpClient) {
    this.clusterUrl = 'localhost:8080/clustertool/singleGene';
  }
  getCell(): Observable<any> {
    return this.http.get(this.clusterUrl);
  }
}

应用路由模块

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

网络控制器

package singleCell.controllers.WebController;

import org.springframework.web.bind.annotation.*;
import singleCell.DatabaseAccess.DAO.DatabaseRetriever;
import java.util.ArrayList;
import java.util.List;

@RestController
@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping("/clustertool")
public class ClusterController {

    @RequestMapping(value = "/singleGene", method = RequestMethod.GET)
            public ArrayList singleGeneResponse(@RequestParam String gene){
        return DatabaseRetriever.getSingleGene(gene);
    }

    @RequestMapping(value = "/multipleGenes", method = RequestMethod.GET)
    public ArrayList multipleGeneResponse(@RequestParam List<String> genes){
        System.out.println(genes);
        return DatabaseRetriever.getMultipleGenes(genes);
    }

}

我希望将后端结果发送到前端,所以我可以在那里进一步使用它。将使用 js 库从数据中绘制图表。

标签: angularrestspring-boot

解决方案


首先,你ClustertoolService.getCell()应该接受一个参数gene

getCell(gene: string): Observable<any> {
  return this.http.get(this.clusterUrl+'?gene='+gene);
}

然后,您应该在提交带有输入值的表单时调用此方法。

onSubmit() {
  this.clustertoolService.getCell(this.geneModel); // geneModel is ngModel for your input.
}

编辑:在您的 HTML 中,您需要在基因输入字段上定义 ngModel

<input type="text" class="form-control" id="gene" [(ngModel)]="geneModel" required>

推荐阅读