Home > Software design >  Passing query param to api in Angular
Passing query param to api in Angular

Time:05-21

Noob angular question here. I have a child component, in which, after button press it pass a form field to a father component. I have to pass this fields as query Params to an API GET /valuation/ that require more or less 20 optional parameters, in which the name differs from Input fields.

I created a temporary object res inside the father function accept in which I iterate the field . Still I can't figure how to pass this parameter inside the object res, using multiple if is dirty code.

for example Function in father component

    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);
      }
      }

As you can see this is not a viable option, what I can use to take dinamically the query param names?

CodePudding user response:

You can use a map to store information about which property from the form maps to which property on your res object and then iterate through the keys, check for the presence of the value and assign:

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);
}
  • Related