Converting a custom object into a params-object in Typescript/Angular 12

I am seeking to utilize the fromObject property of HttpParamsOptions in order to convert a custom object into a params-object.

Here is an example where it works:

foo(): void {
   const testObject = {
     id: 123;
     name: 'test';
     someExample: 'test';
   }
   const httpParams = new HttpParams({ fromObject: testObject });
   ...
}

However, in this scenario it does not work:

export interface SearchParams {
  id: number;
  name: string;
  someExample: string;
}

foo(testObject: SearchParams): void {
   const httpParams = new HttpParams({ fromObject: testObject });
   ...
}

The issue arises when I define the object type using fromObject.

Error: TS2322: Type 'SearchParams' is not assignable to type '{ [param: string]: string | number | boolean | readonly (string | number | boolean)[]; }'.   Index signature is missing in type 'SearchParams'.

Do you have any suggestions on how to resolve this? I am working with Angular 12.

Answer №1

Here is a simple solution:

   const httpParams = new HttpParams({ fromObject: {...testObject} });

The issue arises because the parameter type SearchParams does not align with the type expected by fromObject:

    fromObject?: {
        [param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>;
    }; 

Essentially, the fromObject parameter accepts any literal object.

You can achieve the same result in a few alternative ways. For instance...

Creating a literal object (as you have done):

    const testObject = {
      id: 123;
      name: 'test';
      someExample: 'test';
    }
    const httpParams = new HttpParams({ fromObject: testObject  });

Creating an object by copying from another using the spread operator:

    const myObject = { ...testObject };
    const httpParams = new HttpParams({ fromObject: myObject  });

Alternatively, casting as any type:

   const httpParams = new HttpParams({ fromObject: testObject as any });

According to the typescript documentation on the any type:

The any type is useful when you don’t want to write out a long type just to convince TypeScript that a particular line of code is okay.

Another option is to modify the SearchParams interface to be compatible with the type expected by the fromObject parameter:

  export interface SearchParams {
    id: number;
    name: string;
    someExample: string;
    [param: string]: string | number;
  }
    
  foo(testObject: SearchParams): void {
    const httpParams = new HttpParams({ fromObject: testObject });
  }

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

Performing a series of Http Get requests in Angular 2 with an array that can

Seeking assistance with an Observable http sequence that involves making two dependent http calls to an api. The first call returns an Array of Urls, and the second call makes get requests for each url in the array and then returns the responses on the str ...

Struggling to locate a declaration file for the 'cloudinary-react' module? Consider running `npm i --save-dev @types/cloudinary-react` or exploring other options to resolve this issue

Currently, I am working with Typescript in React. Strangely, when I try to import the following: import { Image } from 'cloudinary-react'; I encounter this error: Could not find a declaration file for module 'cloudinary-react'. ' ...

How can we track and record NaN values in JavaScript/TypeScript as they occur in real-time?

Is there a reliable method to identify and prevent NaN values during runtime, throughout all areas of the application where they might arise? A) Are there effective linting tools available to alert about possible occurrences of NaN values within specific ...

Angular is sending a parameter with a null value, which is not supposed to happen

My filtering system used to work well with a code that displayed items of specific status. However, I had to modify it to match a select input requirement. <ul id="dropdown-basic" *dropdownMenu class="dropdown-menu" role="menu" aria-labelledby="button- ...

Exploring how Django utilizes sessions in conjunction with Angular's cookies while integrating with Django Rest

Looking for a comprehensive example demonstrating how Django Rest Framework can send a session key to Angular for storage as a cookie. I've been trying to figure this out for days... I have Django running on port 8000 and in Angular's ng serve, ...

Reordering items in Angular2 ngFor without having to recreate them

I am facing a unique situation where I must store state within item components (specifically, canvas elements) that are generated through an ngFor loop. Within my list component, I have an array of string ids and I must create a canvas element for each id ...

Adding a ng-select field when a button is clicked

In my template, I am using ng2-select to allow users to select items. There is a button called "Add" that, when clicked, should display another select field with a list of different item categories. However, the current version of my code does not achieve ...

The Angular Material Autocomplete component fails to show items upon upgrading the angular/material package to the newest version

Issue with Angular Material Autocomplete component not displaying items after updating angular/material package to the latest version. The autocomplete was functioning correctly with "@angular/material": "^2.0.0-beta.10" but encountered issues when update ...

There are two modals present on the page, however only one of them is triggered for all actions in Angular 2

I'm encountering an issue with my page where I have set up two confirmation modals - one for resetting a form and another for deleting an item. Strangely, only the reset modal is being triggered for both actions and I can't figure out why. Could ...

Updating a string's value in Angular based on user input

I am currently developing a custom offer letter template that will dynamically update key data points such as Name, Address, Role, Salary, etc based on the selected candidate from a list. The dynamic data points will be enclosed within <<>> in ...

Tips for utilizing angular and express to transmit data via a server and troubleshooting a 404 error

I am currently working on integrating user registration functionality in my frontend using Angular and sending the data to a server (Express). I seem to be facing some issues with the implementation. Does anyone have a solution to this problem? I have set ...

Testing with mount in React Enzyme, the setState method does not function correctly

I've been experimenting with testing this code block in my React App using Jest and Enzyme: openDeleteUserModal = ({ row }: { row: IUser | null }): any => ( event: React.SyntheticEvent ): void => { if (event) event.preventDefault(); ...

What is the process for adding color to an Object3D Object in ThreeJs?

My project involves importing Objects from a file, and I want to be able to color them by clicking on them. After attempting the following code: let mat = (this.scene.children[4].getObjectByName(intersects[0].object.name) as THREE.Mesh).material.color.set ...

Encountering a GitHub REST API CORS issue while attempting to fetch a public repository's git archive

I'm currently working on developing an Angular application that will be hosted on my GitHub pages using a custom verified domain. Below is the code I am using to call the GitHub API in order to obtain the zip archive of one of my (public) repositori ...

Utilizing Angular to Build a Single Router with Numerous Components

Within my Angular application, I am facing a challenge with two components: DashboardComponent and LoginComponent. When a user accesses the URL http://localhost:4200, I need to display the LoginComponent if the user is not logged in. However, if the user i ...

Is Angular 4 failing to set headers properly or is Express.js searching in the wrong place?

When interacting with an Express.js API, I encountered a issue regarding the handling of auth tokens. The problem arose when sending the token in the request headers using Angular 4 compared to Postman. In Postman, setting the header named 'Authorizat ...

tips for converting a single observable item into an observable list

Within my Angular project, there exists an observable object with the following structure: export interface FavoritesResponse { wallet: boolean; deposit: boolean; withdraw: boolean; transfer: boolean; exchange: boolean; ticket: boolean; accou ...

Unable to properly display date formatting in AG-Grid using the Angular date pipe

Currently, I am utilizing ag-grid in conjunction with Angular 8. Within my table, there is a column where my intention is to exhibit dates in a concise format. In order to achieve this, I opted to utilize the Angular date pipe. However, it appears that the ...

What is the best ECMAScript version to select for implementing the TypeScript compiler in an Electron application?

In my Electron 5.0.6 project, I currently have es3 as the default target in my tsconfig.json file. However, I received an error message indicating that I need to upgrade to at least es6 to utilize getter/setter functionality in TypeScript. I am now contem ...

The module 'json-stringify-safe' could not be located

Encountering an issue while executing the command - ionic serve The code was functioning properly on a different system but seems to be causing trouble for me at the moment. https://i.sstatic.net/X1JG0.png ...