Search code examples
angularangular-httpclient

Querying data with parameters using httpClient with Angular13


I'm using Angular 13 and I can pull data with httpClient. But I want to pull data by sending parameter.

How can I do this by sending parameters like below?

inventory.ts

this.inventoryService.getInventoryAllList(this.page, this.pageSize).subscribe({
      next: (data) => {
        console.log(data)
      },
      complete: () => {

      },
      error: (e) => {

      }
    });

inventoryService.ts

    getInventoryAllList(page: number, pageSize: number) {
      return this.httpClient
        .get<{data: InventoryModel[]}>(constants.GET_INVENTORY_LIST_URL+`/${page}/${pageSize}`)
        .pipe(retry(constants.HTTP_SERVICE_RETRY), catchError(this.handleError));
    }

the parameters i want to send can change constantly so i want to send it as variable

categoryId, categoryId, brandId, model Id. I send these sometimes, sometimes; I am sending categoryId and categorySubId. Sometimes I send categoryId so I always send different


Solution

  • You can pass your parameters to the server as http query parameters.

    I usually include in all my projects a function dynamically generates the query parameters string given a record of parameters.

    function buildQueryParameters<T extends Record<string, string | boolean | number | (string | boolean | number)[]>>(queryParameters?: T): string {
      if (!queryParameters) return '';
    
      const params = Object
        .entries(queryParameters)
        .filter(([, value]) => value != null)
        .flatMap(([param, value]) => {
          if (Array.isArray(value)) {
            return value
              .filter(v => v != null)
              .map(v => `${encodeURIComponent(param)}=${encodeURIComponent(String(v))}`)
          }
    
          return [`${encodeURIComponent(param)}=${encodeURIComponent(String(value))}`];
        });
    
      return params.length ? `?${params.join('&')}` : '';
    }
    

    In your service you can change the getInventoryAllList method signagure to accept your parameters and than generate the request URL accordingly:

    // Somewhere in your code
    export type InventoryListParameters = {
      // Here you should specify all your parameters and parameters type to let typescript handle type checking for you
    
      // Example
      categoryId?: string;
      categorySubId?: string;
      brandId?: string;
      modelId?: string;
      anotherParameter?: number;
    
      // [...]
    }
    
    getInventoryAllList(page: number, pageSize: number, parameters?: InventoryListParameters) {
      const resourceUrl = `/${page}/${pageSize}${buildQueryParameters(parameters)}`
    
      return this.httpClient
        .get<{data: InventoryModel[]}>(constants.GET_INVENTORY_LIST_URL + resourceUrl)
        .pipe(retry(constants.HTTP_SERVICE_RETRY), catchError(this.handleError));
    }
    

    You can than use this function as follows:

    // Somewhere in your component
    this.inventoryService
      .getInventoryAllList(this.page, this.pageSize, {categoryId: 'my-category', categorySubId: 'sub-category-id'})
      .subscribe({
        next: (result) => console.log(result),
        error: (error) => console.error(error),
        complete: () => console.log('done')
      })
    

    Update:

    I've updated the buildQueryParameters to support 'multiple' values per parameter name (e.g. if you want to generate '?filter=1&filter=13' or something similar)