From URLSearchParams to HttpParams: A Guide for Angular HttpClient

Facing an issue while updating from Http to HttpClient in a service.ts file on Angular8.

I've made the necessary changes from Http and Headers to HttpClient and HttpHeaders, as well as removed '.pipe(map((response) => response.json().response));'. The options for search:params.toString() were not working with HttpParams, so I switched to params only. However, the requests are not functioning as expected :(

Before (Http)

...

After (HttpClient)

...

Answer №1

Assuming that the variable this.http is indeed of type HttpClient, we need to consider the type definition for HttpClient.get(). According to the definition, the options argument may contain an optional property called params with the type:

params?: HttpParams | { [param: string]: string | string[]; };

It's important to note that this property cannot be just a single string, as returned by params.toString(). It should either be a key-value object containing strings or an instance of the HttpParams class.

Since your params variable aligns with the type

HttpParams</code, you can directly pass it without any conversion.</p>
<p>Instead of:</p>
<pre><code>{ headers: this.headers, params: params.toString() }

You should use:

{ headers: this.headers, params }

However, it seems like in both cases, the params variable remains empty. Unless there are omitted portions where values are added to it during initialization.

Edit:

After reviewing your complete code, the reason behind the empty state of params becomes clearer.

In the case of the URLSearchParams class, the set() method acts as a void function, meaning it alters the existing object without returning anything. The original approach involved setting multiple values and then converting the object to a string (segments involving params.set() were not originally shared).

(method) URLSearchParams.set(name: string, value: string): void

Sets the value associated with a specified search parameter. If other values exist, they get replaced.

Conversely, the behavior of the HttpParams class differs. Each call to params.set() creates a new instance rather than updating the current one.

(method) HttpParams.set(param: string, value: string): HttpParams

Substitutes the value for a given parameter.

@param param — Parameter name.

@param value — New value.

@return — Updated body with the fresh value.

The issue here lies in failing to assign the return value of params.set() back to the main params variable. To rectify this, replace each occurrence of const params with let params to enable overwriting. Furthermore, change all instances of params.set() to params = params.set(). For example:

let params: HttpParams = new HttpParams();
params = params.set('page', page.toString());
params = params.set('size', size.toString());
params = params.set('sort', sort);

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

Problem with Packaging Angular and Spring Boot Applications

My current project structure consists of a spring boot angular project +--app-ui |--+--src |--+--dist |--app-backend |--+--src |--+--+--main |--+--+--+--resources |--+--+--+--+--static |--+--+--+--java The app-ui directory contains the Angular 6 code, wh ...

Angular 7: Show selected value upon clicking Radio button

I am having an issue with a radio button where I need to display a value when it is clicked. For example, when the "weekly" option is selected, I want it to display "Weekly" in the "Selection" element. I have tried to implement this but it is not working a ...

Is it possible to nest a component within another component in the latest iteration of Angular2?

Currently in angular2 version (V2.2.0), I am interested in utilizing a component within another component. In the past, we were able to achieve this by using the following code: import { AnotherComponent } from './another-component'; @Componen ...

Using a dynamic image source in an Ionic 3 background

I am using ngFor to display a list of posts, each of which should have a unique background image. The getBackgroundStyle function is responsible for extracting the URL of the image from the post array. <div class="singlePost" *ngFor="let post of da ...

Application of Criteria for Zod Depending on Data Stored in Array Field

I am currently working on an Express route that requires validation of the request body using Zod. The challenge arises when I need to conditionally require certain fields based on the values in the "channels" field, which is an array of enums. While my cu ...

The variable 'isSideBarOpen' is not a recognized property on the object 'AppComponent'

This is the HTML code snippet for my component: <div> <mat-sidenav-container class="main-container"> <mat-sidenav #sideBarRef opened mode="side" [(opened)]='isSideBarOpen'> <mat-nav-list> ...

Angular 6's Grouping Feature: The Art of Nesting FormArrays

Hello there. In my search for a solution, I've come across similar questions to mine. However, I believe my question has a unique twist and is not a duplicate. Here's the HTML form snippet: <div class="form-group col-md-6" formGroupName="sc ...

Removing API request in React.js

My approach: deleteSample = () => { this.sampleService .deleteCall(this.props.id) .then((response) => { window.location.reload(false); }) .catch((error) => { console.log ...

Angular form retains the previous value when saving

I encountered an issue with my form component where it displays previous values instead of updated ones during a save operation. The strange part is that if I close the form and reopen it, the new values are then shown correctly. It seems like the problem ...

Learn how to effectively utilize the onload event in Angular 2 when working with dynamically inserted image sources

How do I set specific flags once an image finishes downloading? I attempted to use the onload event on the image tag and call a function. However, the implementation below is throwing an error: Uncaught ReferenceError: imageLoaded is not defined ...

Improve your typing accuracy by enforcing strict null checks

I'm currently looking to enable strict null checks in my TypeScript 2.0 project, but I'm encountering some challenges with the typings of a dependency that is nested within another dependency (referred to as the dependency grandparent). To provi ...

Using Angular to display asynchronous data with ngIf and observables

In cases where the data is not ready, I prefer to display a loader without sending multiple requests. To achieve this, I utilize the as operator for request reuse. <div class="loading-overlay" *ngIf="this.indicatorService.loadingIndicators[this?.indic ...

Converting a Typescript project into a Node package: A step-by-step guide

I'm currently dealing with an older typescript project that has numerous functions and interfaces spread out across multiple files. Other packages that depend on these exports are directly linked to the file in the directory. My goal is to transition ...

I'm facing issues with the angular-stl-model-viewer in my current Angular project

I recently attempted to incorporate an stl-viewer into my Angular project using the npm package angular-stl-model-viewer and managed to install all necessary dependencies without any issues. However, I encountered a problem where the viewer is not displayi ...

Building a Custom Dropdown Select List with FormControlName and ControlValueAccessor in Angular 8

Does anyone have a working solution for creating a Material dropdown wrapper (mat-select dropdown) that can be used with formControlName? If so, could you please share a Stackblitz demo of your implementation? Here are the requirements: Should work seam ...

Navigate to a different directory within Cypress by utilizing the cy.exec() function

Dealing with cypress to execute a python script in another directory. However, it seems like the directory change is not functioning as expected. visitPythonProject() { cy.exec("cd /Users/**/Desktop/project/"); cy.exec("ls"); // thi ...

Can the contents of a JSON file be uploaded using a file upload feature in Angular 6 and read without the need to communicate with an API?

Looking to upload a JSON file via file upload in Angular (using version 6) and read its contents directly within the app, without sending it to an API first. Have been searching for ways to achieve this without success, as most results are geared towards ...

Building an Event Scheduler in Outlook Calendar with Angular 5

Currently, I am utilizing Angular version 5.2 for a room booking portal project. One of the requirements entails adding an event to the Outlook calendar on the day a room is booked. The system includes a table listing all bookings, with a button in each ro ...

Angular Object

I am currently working on a small Angular project that focuses on displaying and managing bank accounts using CRUD operations, including transactions. However, I have encountered an issue that is puzzling me. Whenever I click on one of the listed accounts, ...

Challenges with displaying css/bootstrap classes within angular2

Experiencing difficulties with CSS/Bootstrap integration when displayed in an angular2 component. When attempting to display the CSS and HTML content in the Index.html file (with proper CSS and JS references), everything functions correctly. However, once ...