The HttpHeaders argument cannot be assigned to the headers parameter due to type incompatibility

TS2769: No overload matches this call.
The last overload gave the following error.
Argument of type 'HttpHeaders' is not assignable to parameter of type '{ headers?: HttpHeaders | { \[header: string\]: string | string\[\]; } | undefined; context?: HttpContext | undefined; observe?: "body" | undefined; params?: HttpParams | { ...; } | undefined; reportProgress?: boolean | undefined; responseType?: "json" | undefined; withCredentials?: boolean | undefined; }'.
Property 'headers' is private in type 'HttpHeaders' but not in type '{ headers?: HttpHeaders | { \[header: string\]: string | string\[\]; } | undefined; context?: HttpContext | undefined; observe?: "body" | undefined; params?: HttpParams | { ...; } | undefined; reportProgress?: boolean | undefined; responseType?: "json" | undefined; withCredentials?: boolean | undefined; }'.

19     return this.http.post(this.url + 'unique-contacts-reached/', Date, this.httpOptions)


node_modules/@angular/common/http/index.d.ts:2585:5
2585     post\<T\>(url: string, body: any | null, options?: {
\~\~\~\~
The last overload is declared here.

Implementation:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import { throwError } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DashboardService {
  private httpOptions;
  url= 'http://127.0.0.1:8000/dashboard/';
  constructor(private http: HttpClient) {
    const token = localStorage.getItem('token');
    const headers = new HttpHeaders({ 'Content-Type': 'application/json' , 'Authorization' : 'JWT' + ' ' + token});
    this.httpOptions = headers;
  }
  unique_contacts_reached(Date: any){
    return this.http.post(this.url + 'unique-contacts-reached/', Date, this.httpOptions)
  }
}

The issue arises on this line:

unique_contacts_reached(Date: any){
    return this.http.post(this.url + 'unique-contacts-reached/', Date, this.httpOptions)
  }

Answer №1

When utilizing the HttpClient.post() method, ensure that the third parameter expects a value of type object containing a headers property, rather than using a value with type HttpHeaders.

To make the necessary adjustment, update the httpOptions as shown below:

this.httpOptions = {
  headers: headers
};

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

What is the best way to handle and showcase the retrieved values in ngOnInit through filtering?

Is it possible to display the values of fastFoodShopList, bakeryShopList, generalStoreList variables on the screen without actually showing them? Although I can confirm that the value is being retrieved using console.log, it seems like the screen is being ...

Using Typescript with React to pass a class as an argument to an external function

How can I effectively reuse functions as methods across different React classes in Typescript, ensuring compatibility and proper typing? I am trying to achieve something similar to the following... // function to be reused across classes const func = (cl ...

Manipulating variables in a page from a different page in Angular 7: How to control a variable in dashboard.page.ts from landing-in.page.ts

Hey, I'm a newcomer to Angular 7 and Ionic 4. How can I manage variables on the dashboard page from another page? I attempted a simple logic in my application by controlling tbFor with the setToolbar function at dashboard.page.ts from landing-in.page ...

Transmitting JSON and FormData between Angular and Spring

Angular Tutorial processRegistration(user: any, file: File): Observable<any>{ let formData = new FormData(); formData.append("user", JSON.stringify({username:'User'})); formData.append("file", file); return this. ...

Angular compilation error - Invalid selector: %

Whenever I execute npm run build, which in turn runs ng build -c production, the build process completes successfully. However, throughout this process, the command prompt displays a warning message: Warning: 303 rules skipped due to selector errors: 0% ...

The button is obscured by the dropdown menu

Here is the code snippet I am working with: HTML <nav class="navbar bg-dark navbar-dark"> <div class="container-fluid"> <div class="navbar-header"> <a href="#" class=&quo ...

Disable the yellow curly error lines in Visual Studio Code

Currently, I am utilizing VSCode with ESlint for Typescript development. I'm curious about how to turn off or remove the yellow curled error lines in my code editor, like the ones displayed in this example image: https://i.stack.imgur.com/Zdtza.png M ...

Tips on assigning a selected option value to the upload file

The user interface has a selection of documents for the user to choose from. I am trying to associate the fileType with the image that will be uploaded through the input tag. Although I can retrieve the value of the selected document from the drop down usi ...

Minor mistake in locating a RESTful service

I am facing an issue with my project which was developed using Angular and Spring Boot. The Angular part of the project sends requests to the backend. Currently, I have two environments set up - development and staging. The project works fine in the develo ...

(TS 2556) I'm puzzled as to why a type error is being thrown for a spread argument that was clearly defined and passed as a rest parameter

function debouncePromise<TParams extends Array<unknown>, TRes>( fn: (a: TParams) => Promise<TRes>, time: number, ) { let timerId: ReturnType<typeof setTimeout> | undefined = undefined; return function debounced(...args: TP ...

Utilizing External Libraries in Angular Full Stack Development

Currently, I am delving into the realm of Angular Full stack which incorporates Angular 2. As a newcomer to this technology, I have noticed that the setup and structure between pure Angular 2 and the Full stack can be quite distinct. This has led me to enc ...

What is the best way to locate an item within a Redux array when working with TypeScript?

Below is the content of my slice.ts file. interface iItem { Category: string; Id: string; } interface iDataState { Items: Array<iItem>; } const initialState: iDataState = { Items: [], }; reducers: { updateItem: (state, action: PayloadAc ...

How does the order of objects in an array change when using *ngFor in Angular with a .subscribe() method in Ionic 3?

As a newcomer to Ionic 3 & Angular, I encountered a challenge with the *ngFor and .subscribe() method. Please bear with me if this question seems simple. I attempted to understand the behavior of the http.get(..).map(..).subscribe() function when combined ...

Dynamic TypeScript property that can only be assigned values from an array during runtime

I'm currently struggling with specifying allowed values for a property in TypeScript. Within my interface, I have statically typed the property like this: interface SomeInterface{ prop: "bell" | "edit" | "log-out" } However, I am looking for a w ...

Route mismatch

It's showing an error message saying it can't match any routes, but I have clearly defined the route I'm using here: { path: 'categories', component: CategoriesComponent, }, { path: 'categories/:id', ...

ES6: Module 'mongoose' does not seem to have a default export

When working with ES6 Imports & Exports, I initially tried to declare the import statement as import mongoose, { Schema, Document } from 'mongoose';. Unfortunately, this led to an error stating Module '"mongoose"' has no default export ...

What is the process of obtaining a body response through Interception?

I'm currently using Angular and I need to capture the body request in my interception method. Here is what I have tried so far: return next.handle(request).pipe( catchError(err => { return throwError(err); })) I at ...

Error message on Angular 4: "404 - Unable to locate file

Currently, I am working with Angular 4 and attempting to load .csv data. For reference, I have been following this guide: . However, I am facing issues while trying to load the sample.csv file. Despite trying to place the file in src/app, src, or root dire ...

Merge different JSON files to generate a new JSON file

I am faced with a challenge involving 2 separate JSON files. Here is the content of each: User.json: { "users": [ { "username": "User1", "app": "Git", "role": "Manager" }, ...

Guide to encoding an array of objects into a URI-friendly query string using TypeScript

Just getting started with typescript and looking for some help. I have an input array structured like this: filter = [ { field : "eventId", value : "123" }, { field : "baseLocation", value : "singapore" } ] The desired format for ...