将查询参数传递给 Angular 中的 api

Passing query param to api in Angular

菜鸟 angular 问题在这里。 我有一个子组件,在按下按钮后,它会将一个表单字段传递给父组件。我必须将此字段作为查询参数传递给需要或多或少 20 个可选参数的 API GET /valuation/,其中名称与输入字段不同。

我在父函数 accept 中创建了一个临时对象 res,我在其中迭代了该字段。我仍然不知道如何在对象 res 中传递此参数,使用多个 if 是脏代码。

例如 父组件中的函数

    accept(form:any){
        const req: any = {};
        if(form.name)
          req.user = form.name
        if(form.address)
          req.clusterAddress = form.address
       ... and so on x 20 times

this.requestService.getRequest(req).subscribe(
      (response) => {
        this.getRequest(response);
      }, (error) => {
        console.error(error);
      }
      }

如您所见,这不是一个可行的选择,我可以使用什么来动态获取查询参数名称?

您可以使用 map 存储有关 属性 从表单映射到 res 对象上的 属性 的信息,以及然后遍历键,检查值是否存在并分配:

const formToResMap: { [key: string]: string } = {
  name: 'name',
  address: 'clusterAddress',
  // ...
};

accept(form: any) {
  const req = Object.keys(formToResMap).reduce((acc, key) => {
    if (form[key]) {
      acc[formToResMap[key]] = form[key];
    }
    return acc;
  }, {});
  console.log(req);
}