0

Here is the http-service -

  public getProducts(
    gender?: ProductGender,
    category?: ProductCategory,
  ): Observable<IGetProductsResponse> {
    const baseUrl = ENDPOINT;

      return this.http.get<IGetProductsResponse>(
        `${baseUrl}list?gender=${gender}&category=${category}`
      );
  }

If I'm sending the request like this, i get 0 as the value I'm not filling. for example -

http://localhost:4200/product-list?gender=1

I'll get the category value as 0.

How can i use the URL in a way that able to get only gender or category?.

Tried to change the URL to - ${baseUrl}list?gender=${gender} and that is working but it is not dynamic.

2 Answers 2

1

I would use HttpParams instead, to build the parameter list however you need, rather than passing them manually like in your code. You can try this and see how it works:

  public getProducts(
    gender?: ProductGender,
    category?: ProductCategory
  ): Observable<IGetProductsResponse> {
    const baseUrl = ENDPOINT;
    const params = new HttpParams();

    if (gender) {
      params.append('gender', gender);
    }

    if (category) {
      params.append('category', category);
    }

    return this.http.get<IGetProductsResponse>(`${baseUrl}list`, { params });
  }
Sign up to request clarification or add additional context in comments.

Comments

0

You could declare a ternary parameter variable and inject that into your URL string.

const param = !!gender ? `gender=${gender}` : `category=${category}`;

return this.http.get<IGetProductsResponse>(`${baseUrl}list?${param}`);

Since 0 is falsy, you can just use double bangs to evaluate gender.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.