Home > Back-end >  How can i make my query parameters to be type safe?
How can i make my query parameters to be type safe?

Time:09-24

I have maked service where I need to send query parameters dynamically.

METHOD SERVICE So I have this method in my AuctionService.

getBids(id:number, params?: any) {
  return this.http.get(this._GET_AUCTION_URL   '/'   ApiPaths.auction   '/'   id   '/bids', {params});
}

From my component when I send the query parameters

COMPONENT.ts

  let queryParams = {
      filterSupplierName: 'sds',
      filterBidAwardStatus: ['Awarded', 'Ignored']
    }

 this.getAuctionService
    .getAuctionBidsByGuidUsingGET(id, queryParams)
    .subscribe((data) => {
...

it makes dynamically the GET url to be like so

https://some-url/api/22222/bids?filterSupplierName=sds&filterBidAwardStatus=Awarded&filterBidAwardStatus=Ignored

NOW I WANT TO MAKE TYPE SAFETY IN MY query params, so from component when I try to send for example some property which key or values is not correct, to show some compilation error.

So I need to have filterSupplierName of type string OR filterBidAwardStatus OF type array of string.

So when I try that

export interface IBidsFilter {
  filterSupplierName: string;
  filterBidAwardStatus: string[];
}
getBids(id:number, params?: IBidsFilter) {
  return this.http.get(this._GET_AUCTION_URL   '/'   ApiPaths.auction   '/'   id   '/bids', {params});
}

I get error No overload

No overload matches this call.
  The last overload gave the following error.
    Type 'ITest' is not assignable to type 'HttpParams | { [param: string]: string | string[]; }'.
      Type 'ITest' is not assignable to type '{ [param: string]: string | string[]; }'.
        Index signature is missing in type 'ITest'

The only solution that I found is adding as any but it is not so good solution

getBids(id:number, params?: IBidsFilter) {
  return this.http.get(this._GET_AUCTION_URL   '/'   ApiPaths.auction   '/'   id   '/bids', {params: params as any});
}

How can I solve this with another solution?

CodePudding user response:

Angular HTTP client expects query parameters with string types only because you can only send string in a URL in the end.

That is it expects params to be of type { [key:string] : string | string[] }. (actually it allows some other variations but that's the idea)

This means you should convert your IBidsFilter to the type above.

Note that your error talks about a ITest that is not part of IBidsFilter, I assume you didn't copy the whole definition.

CodePudding user response:

You can do this with HTTPParams()

let queryParams = new HttpParams();
let arr = [‘abc’,’def’,’ghi’,'jkl'];
queryParams.append('test',arr[0]);
queryParams.append('test',arr[1]);
queryParams.append('test',arr[2]);
queryParams.append('test',arr[3]);

return this.http.get('url', queryParams);
  • Related