如何将Angular HTML表单输入发送到Spring Boot Rest Web控制器

时间:2019-05-27 12:54:02

标签: angular rest spring-boot

我正在尝试通过角度前端和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库从数据中绘制图表。

1 个答案:

答案 0 :(得分:0)

首先,您的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>