角度带有可变数量参数的形式输入

时间:2019-06-18 11:11:09

标签: angular

我正在编写一个程序,可以在我的输入形式中获得1个或多个基因名称。如果我有一个,我想运行到后端的某个API链接。如果我能得到更多,我想经营另一家。处理此问题的最佳方法是什么?我希望用户能够键入一个列表,例如:cd19或4f5 ms4a1,然后按提交按钮。

最好的方法是让我的onSubmit处理单个和多个参数,还是应该使用单选按钮,以便用户可以指定是否要提供1个或多个参数?如果可能的话,我会首选第一种方法,因为它在前端看起来更干净。随意提出其他我尚未想到的建议。

//my current form that can only accept a single argument at this moment.
<div class="container">
  <h1>Clustertool gene(s) input</h1>
  <form name="form" (ngSubmit)="onSubmit()">
    <div class="form-group">
      <label for="gene">gene(s) </label>
      <input type="text" class="form-control" name="gene" [(ngModel)]="model.gene" #gene="ngModel" required>
    </div>
    <button type="submit" class="btn btn-success" ng-disabled="!form.$valid"> Submit</button>
    </form>
</div>

此方法调用我的服务,该服务将API请求发送到我的后端

onSubmit() {
    if(this.model.gene)
    this.clustertoolService.getCell(this.model.gene).subscribe(val => {
      this.cell = val;
      this.clusterCell();
    });
  };

这是我的服务,目前只能要求一个基因。我将添加使用多个的第二种方法,但是我不确定如何执行此操作,也许是for循环,为提供的每个参数添加“ +'?gene ='+ gene”?

export class ClustertoolService {
  private clusterUrl: string;

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

    return this.http.get(this.clusterUrl+'?gene='+gene);

  }

}

我的调用后端的控制器类。

@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){
        return DatabaseRetriever.getMultipleGenes(genes);
    }
}

1 个答案:

答案 0 :(得分:0)

将字符串拆分为一个数组,然后检查大小

getCell(geneString: string): Observable<any> {
    const urlRoot = 'http://localhost:8080/clustertool/';
    const geneArray = geneString.split(' ');

    return this.http.get(
        urlRoot + (geneArray.length === 1 ? 'singleGene' : 'multipleGenes'),
        {params: {gene: geneString}}
    );
}

请注意,理想情况下,查询参数应指定为传递给params的{​​{1}}参数的options属性的对象,而不是包含在URL字符串中。如果您需要不同的查询参数(取决于您是单端点还是多端点),可以通过类似的条件处理