Screening properties before condensing

I am currently facing an issue where I need to map an Object to HttpParams while excluding any parameter that is empty, null, or undefined.

export function mapToHttpParams(obj: object): HttpParams {
  return Object.getOwnPropertyNames(obj)
    .reduce((p, key) =>
        p.set(key, (typeof obj[key] === 'undefined' || obj[key] === null) ? '' : obj[key]),
      new HttpParams());
}

The above code still includes those empty parameters and I am looking for a solution like:

export function mapToHttpParams(obj: object): HttpParams {
  return Object.getOwnPropertyNames(obj)
    .remove(obj[key] === null && obj[key] === '' && obj[key] === null)
    .reduce((p, key) =>
        p.set(key, (typeof obj[key] === 'undefined' || obj[key] === null) ? '' : obj[key]),
      new HttpParams());
}

I have been unable to find the correct way to achieve this - consistently encountering compilation errors.

Answer №1

Do you need this specific solution:

function convertObjectToHttpParams(obj: { [key: string]: string }): HttpParams {
    const params = Object.keys(obj)
        .filter(key => !!obj[key])
        .reduce((acc, cur) => { acc[cur] = obj[cur]; return acc; }, {} as { [key: string]: string });
    return new HttpParams({ fromObject: params });
}

Answer №2

By skipping the filtering step, you have the option to directly apply the original object to the reduce() method

export function transformToHttpRequestParams(data: object): HttpRequestParams {
  return Object.getOwnPropertyNames(data)
    .reduce((params, key) => data[key] == null || data[key] == '' ? params : params.set(key, data[key]),
      new HttpRequestParams());
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sending Disabled Form Field Input Value in Angular 2 POST Request

I'm working on a form with an email field that I want to populate using interpolation. However, I also want to prevent users from changing the email address once it's displayed. To achieve this, I tried adding the disabled attribute to the input ...

Error encountered while fetching client credentials in Next-Auth Credential-Provider [next-auth]

Exploring the combination of nextjs and next-auth for authentication using a credential provider has been intriguing. However, I've encountered an issue when attempting to access a protected route while logged in: [next-auth][error][client_fetch_error ...

Unable to translate text on the loading page

Encountering a peculiar issue with the translate service. Here's how I set it up: export class AppComponent implements OnInit { constructor( private translateService: TranslateService, angulartics2GoogleAnalytics: Angulartics2GoogleAnalytics ...

Using an additional router-outlet in an Angular 2 application: a step-by-step guide

I have been facing an issue with my angular2 app where I am attempting to use 2 router-outlets. Despite reading numerous blogs and conducting multiple Google searches, I have not been able to make it work. I would greatly appreciate any suggestions on why ...

Encountered an error during the execution of the postinstall script for @angular/[email protected] package

Hey there, I'm having trouble installing the Angular CLI using npm install -g @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f596999cb5cddbc6dbc4cc">[email protected]</a>. Every time I try, I encount ...

How to activate a textbox in Angular 6 when a checkbox is selected:

Looking for examples related to this topic, all I've come across are AngularJs examples. Is there a way to enable my textbox based on the status of a checkbox in the same row, without directly binding them through a boolean value or using JavaScript? ...

Unable to send messages despite successful connection through Sockets.io

My Java Server is set up to listen for messages from an Ionic 2 Client using Sockets.io. The server can successfully send messages to the client, but I am facing issues with getting the client to send messages back to the server. For example, when the jav ...

In the world of GramJS, Connection is designed to be a class, not just another instance

When attempting to initialize a connection to Telegram using the GramJS library in my service, I encountered an error: [2024-04-19 15:10:02] (node:11888) UnhandledPromiseRejectionWarning: Error: Connection should be a class not an instance at new Teleg ...

Identifying data types of objects through generic value recognition

Is there a way to detect the parameter type of a function using the described type and create an object with the same structure, identifying the provided fields and their value types based on the description? Here is an example: // Define the type type St ...

How to retrieve static attributes while declaring an interface

class A { public static readonly TYPE = "A"; } interface forA { for: A.TYPE } I am facing an issue while trying to access A.TYPE from the forA interface in order to perform type guarding. The error I encounter is: TS2702: 'A' only refe ...

Navigating the dot notation to uncover the data type of a field within an object

When working with an object type, we can access the type of one of its fields using bracket-string notation. However, why isn't it possible to use dot notation like in JavaScript? Could there be a conflict or some other reason for this limitation? I h ...

Display issues with deeply nested components

I'm facing an issue with displaying the third nested component. Expected: Hello App Component Hello Nest-A Component Hello Nest-1 Component Hello Test-Z Component Actual: Hello App Component Hello Nest-A Component Hello Nest-1 Component Why ...

Leverage push notifications and utilize multiple service workers with an Angular Ionic 5 progressive web app, designed for optimal performance on Web, Android

Currently facing an issue with my Ionic/Angular Capacitor PWA. In order to enable PUSH NOTIFICATIONS for Web, Android, and IOS platforms, I have focused on setting it up for Web first. The Angular app prompts users for permission to receive notifications ...

Can a map key value be converted into a param object?

I have a map containing key-value pairs as shown below: for (let controller of this.attributiFormArray.controls) { attributiAttivitaMap.set(controller.get('id').value, { value: controller.get('valoreDefault').value, mandatory ...

Using Tokens for Authentication and Authorization in an Angular 4 Application Integrated with an ASP.Net Core API

My app needs to be developed using Angular4 and ASP.Net Core API, with the following requirements: Authentication and authorization will be based on JWT tokens. This application will be accessed by both internal users and external users. Internal users s ...

Encountering the error message 'array expected for services config' within my GitLab CI/CD pipeline

My goal is to set up a pipeline in GitLab for running WebdriverIO TypeScript and Cucumber framework tests. I am encountering an issue when trying to execute wdio.conf.ts in the pipeline, resulting in this error: GitLab pipeline error Below is a snippet of ...

Is there a way to store the outcome of an HTTP GET call in Angular 7 as a JSON file?

Hey there! I'm currently working on a web app that needs to make regular calls to a remote API. Since the response will always be consistent, I am planning to optimize the site's performance by storing the response data in a local JSON file. This ...

Inject components in Angular using dependency injection

Can components in Angular be dependency injected? I am interested in a solution similar to injecting services, like the example below: my.module.ts: providers: [ { provide: MyService, useClass: CustomService } ] I attempted using *ngIf= ...

Is it possible in Firebase to retrieve multiple queries and consolidate them into a collectionData?

In situations where the number of equalities exceeds 10, the "in" operator can be utilized. In such cases, the array can be divided into multiple sub-arrays of size 10 and multiple query requests can be initialized. When the array length is less ...

Unable to modify the color of the bootstrap datepicker

I have implemented a date input using bootstrap-datepicker to provide a calendar for users to select dates. However, I am facing difficulty in changing the background and head's color. Below is my HTML code: <div class="row mb-1"> < ...