Setting null for HttpParams during the call

I am encountering an issue with HttpParams and HttpHeaders after upgrading my project from Angular 7 to Angular 8. The problem arises when I make a call to the API, as the parameters are not being added. Any assistance in resolving this matter would be greatly appreciated.

Below is the method where I set the headers and params:

fetchJson(url: string, parameters ? : any) {
    this.token = this.cookieService.get('access_token');
    this.contrat_token = this.cookieService.get('contrat_token');

    let headers = new HttpHeaders();
    headers = headers.append('Content-Type', 'application/json');
    headers = headers.append('Authorization', 'Bearer ' + this.token);
    headers = headers.append('contrat_token', this.contrat_token);

    let params = new HttpParams()
    params.set('search', parameters);
    console.log('headers');
    console.log(headers);
    console.log('params');
    console.log(params.toString())

    return this._http.get(url, {
        headers,
        params
      }).pipe(map((resp: any) => {
            if (resp.status === 401 || resp.status == 401 || resp.status.toString() == "401") {
              this.clearCookie();
            } else {
              let reponse = resp;

              if (reponse == -1 || reponse == "-1") {
                this.router.navigate(["/"]);
              }
            }

            return resp;
          }

The method is then called within my services like so:

   getDetailThematiquePrevNext(id: string, typeBase: string) {
        let URL = this.urlDecorator.urlAPIDecorate("DI", "GetDetailThematiqueHeaderPrevNext");
        let params = this.urlDecorator.generateParameters({
            id: id,
            typeBase: typeBase,
          
        });
        return this.apiFetcher.fetchJson(URL, params);
    }

Answer №1

The explanation from Cue is accurate; you should use chaining or apply the same approach as you did for headers.

let headers = new HttpHeaders();
headers = headers.append('Content-Type', 'application/json');
headers = headers.append('Authorization', 'Bearer ' + this.token);
headers = headers.append('contrat_token', this.contrat_token);

let params = new HttpParams()
params = params = params.set('search', parameters);

A more organized way of writing this would be:

const headers = new HttpHeaders()
    .append('Content-Type', 'application/json')
    .append('Authorization', 'Bearer ' + this.token)
    .append('contrat_token', this.contrat_token);

const params = new HttpParams().set('search', parameters);

Additionally, you can omit the Content-Type header since JSON is the default format.

Answer №2

It seems that lazy parsing might be the cause of this issue. In order to determine the state, you need to use either get or getAll to access values.

The HttpParams class is used to represent serialized parameters in the MIME type application/x-www-form-urlencoded. This class is immutable and any mutation operations will return a new instance.

On the other hand, the HttpHeaders class represents the header configuration options for an HTTP request. It is recommended to assume that instances are immutable with lazy parsing.

To set your options directly into the instance for both headers and params:

let headers = new HttpHeaders({
  'Content-Type': 'application/json',
  'Authorization': 'Bearer ' + this.token,
  'contrat_token': this.contrat_token
});

let params = new HttpParams({
  search: parameters
});

As mentioned by @Siraj, there are alternative methods to set values for headers and params such as set...

let headers = new HttpHeaders().set('name', 'value');
let params = new HttpParams().set('name', 'value');

Or using append...

let headers = new HttpHeaders().append('name', 'value');
let params = new HttpParams().append('name', 'value');

It is important to remember that these methods require chaining as each method creates a new instance.

You can also convert objects like this:

let headerOptions = {
  'Content-Type': 'application/json',
  'Authorization': 'Bearer ' + this.token,
  'contrat_token': this.contrat_token
}

let headers = new HttpHeaders();

Object.keys(headerOptions).forEach((key) => {
  headers = headers.set(key, headerOptions[key]);
});

Avoid binding objects by reference and instead pass them as parameters:

return this._http.get(url, {
  headers: headers,
  params: params
});

Lastly, since your type annotation is "any" for the parameters argument, params expects HttpParamsOptions where values must be annotated as strings.

let params = new HttpParams({
  search: JSON.stringify(parameters)
});

Try

console.log(params.getAll('search'))
, but for a more accurate check on whether headers and params are being sent, the Network tab in DevTools would be a better place to verify.

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

Adjusting the navigation image as it passes through various div elements during scrolling

Is it possible to dynamically change an image in the navigation bar based on the user's scroll position? For example, I want pic1 to be displayed when the page content is at the top, then switch to pic2 once the user reaches the footer, and then back ...

Is it accurate that JavascriptResult displays javascript on the page in a string format?

I am new to .NET MVC and have been experimenting with different return types in MVC. However, I am having trouble getting the JavaScriptResult to work. In my controller, I have the following code: public ActionResult DoSomething() { string s = ...

The retrieval of data from AWS Dynamodb in Node.js is not done synchronously

I recently started working with Node.js and DynamoDB. I created a Node.js SDK to retrieve a single row from a DynamoDB table. The data is being fetched correctly, but there is a delay which is causing an error. Below is a snippet of my code: var AWS = re ...

NextJs 13 unveils its cutting-edge dynamic sitemap feature

I am currently working on implementing a dynamic sitemap for NextJs 13.4.6, referring to the guide available at . However, I have encountered an issue with the code provided towards the end of the article which is supposed to generate a sitemap for NextJS ...

I'm torn between whether to calculate on the client side for more requests or on the server side for fewer requests. What should I do?

Consider this scenario: I am developing a shopping cart application where I need to store information such as idClient, createdAt, total, and products in each purchase. In addition, I need to apply discounts on the products for each purchase. This is how ...

It is not possible to submit two forms at once with only one button click without relying on JQuery

I need to figure out a way to submit two forms using a single button in next.js without relying on document.getElementById. The approach I've taken involves having two form tags and then capturing their data in two separate objects. My goal is to hav ...

Display a text field when the onclick event is triggered within a for

Control Panel for($i = 1; $i <= $quantity; $i++){ $data .= '<b style="margin-left:10px;">User ' . $i . '</b>'; $data .= '<div class="form-group" style="padding-top:10px;">'; $data .= ' ...

How can I set the background of specific text selected from a textarea to a div element?

Is it possible to apply a background color to specific selected text from a Text area and display it within a div? let elem = document.getElementById("askQuestionDescription"); let start = elem.value.substring(0, elem.selectionStart); let selection = ...

Divs are not being organized into rows correctly due to issues with Bootstrap styling

I have implemented Bootstrap in my Angular application. The stylesheet link is included in my Index.html file as follows: <link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css"> In addition to that, I have listed Bootstrap a ...

Incorporating observables into an existing axios post request

Currently, I have an API using axios to send HTTP POST requests. These requests contain logs that are stored in a file. The entire log is sent at once when a user signs into the system. Now, I've been instructed to modify the code by incorporating Rx ...

Issues with object changes not reflecting in Vue.js 2.0 component rendering

I am facing an issue where my object is not updating immediately after a click event. It appears that a manual refresh or clicking on another element is necessary for the changes to take effect. How can I ensure that the object updates without the need for ...

Anticipated a JavaScript module script, but the server returned a MIME type of text/html as well as text/css. No frameworks used, just pure JavaScript

I have been attempting to implement the color-calendar plugin by following their tutorial closely. I have replicated the code from both the DEMO and documentation, shown below: // js/calendar.js import Calendar from '../node_modules/color-calendar&ap ...

elementToBeClickable is not supported by webdriverio

I am having some trouble with the 'waitForEnabled' function as it does not seem to behave like Webdriver's elementToBeClickable. Is there anyone who can provide some guidance on how to use this API effectively? ...

What is the best way to send JSON data from Express to a JavaScript/jQuery script within a Pug template?

Currently, I am facing a challenge in passing JSON data from an Express route to a .js file located within a .pug template. I have been attempting to solve this issue using the following method: The router: // Office Locations router.get('/office_lo ...

How to implement PayPal integration in PHP

I am currently working on integrating the paypal payment system into a website dedicated to pet adoption. Initially, I had a basic code structure that was functional. However, after making some modifications and additions to the code, it no longer redirect ...

I need assistance with this ajax/javascript/php

I am currently working on creating a dynamic chained list. The idea is to have the user make selections from the first four dropdown lists, and based on their choices, a fifth dropdown list should appear. However, I am facing some issues with my code as th ...

Having trouble with the Angular Material component? The element 'mat-option' is not recognized

I am having trouble with implementing an Angular Material component. The component is not functioning properly, and I received the following error message: Uncaught Error: Template parse errors: 'mat-option' is not a known element: // ... I sus ...

Changes to the parent state will not be reflected in the child props

When the child component PlaylistSpotify updates the state localPlaylist of its parent, I encounter an issue where the props in PlaylistSpotify do not update with the new results. I've been struggling to figure out what I'm missing or doing wrong ...

Ensure that only the most recent Ajax request is allowed

In my project, I have an input box that triggers an ajax request with every key press. This means if I type the word "name," there will be a total of 4 requests sent out. However, what I really need is to only execute the latest request. So even if I enter ...

Stop button from being clicked inside a div when mouse hovers over it

I am facing an issue with a div containing a mouseenter event and a button inside it with a click event. The concept is that when the user hovers over the div triggering the mouseenter event, the div becomes "active", allowing the button to be visible and ...