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

Angular 2: Enhancing Textareas with Emoji Insertion

I am looking to incorporate emojis into my text messages. <textarea class="msgarea" * [(ngModel)]="msg" name="message-to-send" id="message-to-send" placeholder="Type your message" rows="3"></textarea> After entering the text, I want the emoj ...

Refresh the content with an embedded iframe

I am attempting to update the body content by removing all existing content and inserting an iframe: function create_custom_iframe(target){ var iframe = document.createElement('iframe'); iframe.setAttribute('id', 'target_u ...

The "add to cart" button is unresponsive

My issue is that the add to cart button on my website is not responding properly. I have implemented JavaScript on the add to cart button, where I have assigned an attribute called data-product with a value of {{product.id}}. var updateBtns = document.g ...

Employing CSS animations to elevate div elements

Currently, I am working on animating a table of divs and trying to achieve an effect where a new div enters and "bumps up" the existing ones. In my current setup, Message i3 is overlapping Message 2 instead of bumping it up. How can I make Messages 1 and 2 ...

Angular Material Rotate Ink Bar to Vertical Orientation

After wanting to change the orientation of Angular Material's Tab Component to vertical, I visited this page (Tabs) and experimented with the CSS. By making the necessary adjustments, I successfully displayed the tabs vertically using the following CS ...

Guide on setting an instance property through a callback function triggered by the instance

I am looking to set an attribute of an angular service using the result from a callback function. Here is my Angular service: @Injectable() export class SkillsManagerService { private skill: any; private event: any; constructor() { ...

Troubleshooting Issues with AngularJS HTTP.get Requests

I'm currently working on a simple AngularJS application that is supposed to extract data from a .json file. While my code doesn't show any errors upon running it, it fails to retrieve the JSON values as expected. I have a feeling that I may be ov ...

Enhance your website with the latest jQuery plugins and CSS

Currently, I am utilizing jQuery to develop plugins for my application. It is worth noting that each plugin demands a distinct CSS file. What approach should I follow to effectively load both the jQuery file and the respective CSS? Moreover, the plugins ...

Why is the responseText from XMLHttpRequest always stripped of tags in AJAX?

Whenever the server sends the XML string to the client using the XMLHttpRequest object, I noticed that when I insert the text inside the div tags, it appears without any tags. However, I actually need the XML tags to be present so that I can parse the cont ...

What is the best way to ensure a specific section of a website remains visible and fixed at the bottom of the page

I want to set up a simple toolbar with divs and uls containing both anchors and tabs. The position of the toolbar needs to be fixed at the bottom of the page. <%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional/ ...

Passport is raising a "missing credentials" error upon return

Hello everyone! I'm currently working on a password reset form and encountering an issue. When I submit the email in my POST form, I'm seeing a frustrating "Missing credentials" error message. This is preventing me from implementing the strategy ...

Sending data from the View to the Controller in a Razor MVC3 application involves passing a model along with

Within my view, there's a form representing my View model with multiple fields. I aim to generate a list of links for pagination purposes that will not only redirect to a specific page but also send the input data from the form along with it. The Java ...

What is the proper way to add an SSL cert to an Angular HTTP API request?

Is there a need to utilize a certificate when making an API call to retrieve an access token? For example, if the method is POST at getAccess.com/getCode, how should we handle this in Postman with a certificate attached? I am currently working on an Angula ...

Tips for generating a .csv document using data from an array?

I am currently utilizing a PHP class to validate email addresses in real-time. The PHP Script is functioning as expected: validating the emails and displaying the results on the same page by generating a <td> element for each validated email. Howeve ...

I'm curious – what exactly does `useState(null)[1]` do within React hooks?

Recently, I've started utilizing React hooks in my code. There was this interesting syntax useState(null)[1] that caught my attention, although now I can't seem to recall where I first saw it. I'm curious about the difference between useSta ...

Leveraging cloud functions on Firebase for maximum efficiency

Question: Do you require a backend language when using Firebase Cloud Functions, or can TypeScript alone suffice for coding tasks like creating a matchmaking system? Response: There seems to be some uncertainty on the matter even from ChatGPT himself. Is ...

How can I include inline CSS directly within a string instead of using an object?

Is there a way to write inline CSS in a string format instead of an object format? I attempted the following, but it did not work as expected: <div style={"color:red;font-weight:bold"}> Hello there </div> What is my reason for want ...

Enhance DataTables functionality by including the ability to select which script to execute

Currently, I have a DataTables displayed with the provided code, utilizing server-side processing which is functioning properly. I am interested in implementing a dropdown menu above the table that allows users to select from options such as: Product Gr ...

The presence of 'eventually' in the Chai Mocha test Promise Property is undefined

I'm having trouble with using Chai Promise test in a Docker environment. Here is a simple function: let funcPromise = (n) => { return new Promise((resolve, reject) =>{ if(n=="a") { resolve("success"); ...

Maintaining duplicate values in a JSON stringify operation: Tips for retention

Server responses are being received in JSON format, which may contain objects with duplicate keys. When displaying the results, I noticed that only the last value for duplicate keys was showing up. After investigating, I realized this was due to using the ...