In TypeScript and Angular 9, there is an error stating that Type Headers cannot be assigned to type HttpHeaders

As a newcomer to TypeScript, I have been working on a basic authentication tutorial. My choice for the backend is Express, and for the frontend, I am utilizing Angular 9. Despite extensive online research, I couldn't find a solution that matched my particular case.

The error message I encountered reads as follows:

Error: src/app/services/auth.service.ts:19:79 - error TS2769: No overload matches this call. The last overload gave the following error. Type 'Headers' is not assignable to type 'HttpHeaders | { [header: string]: string | string[]; } | undefined'. Type 'Headers' is not assignable to type '{ [header: string]: string | string[]; }'. Index signature is missing in type 'Headers'.

19 return this.httpCient.post('http://localhost:3000/users/register', user, {headers: headers}).pipe(map(res => res));

This issue seems to stem from the same line of code within both the functions registerUser(user) and authenticate(user):

return this.httpCient.post('http://localhost:3000/users/authenticate', user, {headers: headers}).pipe(map(res => res));

Here's the problematic segment of code:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  authToken: any;
  user: any;

  constructor(private httpClient: HttpClient) { }


  registerUser(user) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.httpClient.post('http://localhost:3000/users/register', user, {headers: headers}).pipe(map(res => res));
  }

  authenticateUser(user) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.httpClient.post('http://localhost:3000/users/authenticate', user, {headers: headers}).pipe(map(res => res));
  }
}

While attempting to resolve this issue, I came across a related post, but it didn't provide a suitable solution due to the usage of Angular 9 and the substitution of HttpClient, HttpHeaders for '@angular/common/http';. However, I managed to make some progress based on the information provided.

Another resource that I found useful was this one, which although targeted towards Angular 2, offered some general insights but unfortunately, didn't offer a direct resolution to my problem.

If anyone has encountered a similar error and found a solution, I would greatly appreciate your input.

Answer №1

When using the HttpClient, it requires HttpHeaders as a parameter. The old Headers object is not compatible with the HttpClient. An example of how to use HttpHeaders is shown below:

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json'
});
return this.httpClient.post('http://localhost:3000/users/authenticate', user, httpOptions);

For more details and examples, visit: https://angular.io/guide/http#adding-headers

Remember to subscribe to the returned Observable or else the request will not be sent. (Observables are lazy.)

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

I aim to adjust the width of a logo and ensure its size is fixed for optimal visibility

The selected logo needs to be more visible. I have attempted to use media queries to adjust its visibility, but I am having trouble with it. I want the logo to be able to stretch in width, but I am unsure how to achieve that. Currently, this is what I hav ...

TypeScript combined with Vue 3: Uncaught ReferenceError - variable has not been declared

At the start of my <script>, I define a variable with type any. Later on, within the same script, I reference this variable in one of my methods. Strangely, although my IDE does not raise any complaints, a runtime error occurs in my console: Referenc ...

Can I retrieve the return type of useFetch in Nuxt3?

I am running into an issue while trying to specify the APIBody type in the following manner: Property 'test' does not exist on type 'NonNullable<PickFrom<_ResT, KeysOf>>'. It seems like there is no straightforward way to def ...

Tips for embedding different pages within a single page using Angular 5

My project consists of 4 pages. [ { path: 'page1', component: Page1Component }, { path: 'page2', component: Page2Component }, { path: 'page3', component: Page3Component }, { path: 'page4', component: Page4Co ...

When utilizing a generic type with a class, type T fails to meet the specified constraint

export type ExtractType<T extends Array<{ name: Array<string>, type: keyof TypeMapping }>> = { [K in T[number]['name'][0]]: TypeMapping[Extract<T[number], { name: K }>['type']] } export class CommandLineParse ...

Displaying API responses in Ionic4 application viewer (HTML) is not functioning properly

Having recently delved into Ionic and Angular, I found a helpful tutorial () that guided me in creating a movie app that works across platforms. To further my learning, I decided to switch to using the API instead of the IMDB API. While I am able to retr ...

Combine array elements in Angular/Javascript based on a certain condition

Is there a way to combine elements from two arrays while avoiding duplicates? array = [ {id: 1, name:'abc'},{id: 1, name:'xyz'},{id: 2, name:'text1'},{id: 2, name:'text2'} ]; The desired output is: result = [{id: ...

Is there a way for me to reach the ngFor variable within a different ngFor loop?

Here is an example code snippet to display user details. Currently, we have only one user and three permissions in an array: 1) Users = [{'FirstName':'John','permission':['masters','transactions']}] 2) p ...

Having trouble with ng-select focus in Angular 5?

I've been attempting to implement focus on ng-select within Angular 5, but unfortunately, it doesn't seem to be working as expected. Currently, I am utilizing ng2-select for my project. Is there a specific method for implementing focus on ng-se ...

Unusual occurrences with parameterized functions being passed as props in React

It feels like I'm missing something obvious here and I'm a bit stuck with this problem. Here is the function I have: public handleTest = (testNum: number) => { console.log(testNum); }; Now, I want to pass this function to a component ...

Cannot be assigned to type "never" after applying a type predicate

I'm attempting to merge a method for creating strongly typed strings with type predicates but encountering issues, as evidenced by the following code snippet: https://i.sstatic.net/2b9pO.png The issue I'm facing is TS2339: Property 'substr& ...

Managing Angular 6 HTTP Interceptor for Refresh Token in case of 401 Unauthorized Error

After implementing my AuthInterceptor, I am facing an issue where the handle401Error method does not receive any response when calling this.authService.refreshToken().pipe() upon encountering a 401 error. AuthInterceptor Implementation import { Injectabl ...

Leveraging AnimatePresence from the Framer Motion library to design an exit animation for a motion.div

My goal is to implement a side menu that smoothly slides in and out when the menu/close button is clicked using framer motion. Initially, clicking on the menu button will cause the menu to slide out from the left side of the screen while changing the butto ...

The specified type 'BallInterface' must have 2 type arguments specified

Currently on my Typescript learning journey, I encountered an error that states Generic type 'BallInterface' requires 2 type argument(s) in relation to tennisBall. How can I properly call a function with an object parameter containing multiple ge ...

Extract data from a string and assign it to a variable representing an

I have a custom function that parses a string and converts numbers and boolean values to their appropriate JavaScript primitives. This function is specifically designed for working with query parameters: const parseQueryParams = (searchString: string) => ...

Issue encountered while authenticating client secret from backend for newly created Stripe subscription

There seems to be an issue with confirming the client secret sent from the express backend to the frontend, specifically in a React Native-based mobile application. The clientSecret is being sent in the same manner as described above. On the frontend Rea ...

Error when accessing JSON property in Angular with Ionic 2: A Strange TypeError

I have implemented a provider in my Ionic project to fetch the user object from storage. Below is the code: import { Injectable } from '@angular/core'; import { Storage } from '@ionic/storage'; @Injectable() export class ApiProvider { ...

The proper method for importing third-party JavaScript files in Karma tests for Angular 6

I am facing an issue with my Angular component that uses primeng's ChartsModule which relies on Chart.js. I have successfully installed and imported Chart.js in my project's angular.json file. "scripts": [ "node_modules/chart.js/dist/Chart.bun ...

List of React components created using Typescript

Struggling with rendering a list in React using Typescript. I'm new to Typescript and unsure how to properly pass props from App.tsx to Technology.tsx Vue JS Node JS Angular JS React JS Technology.tsx import React from 'react'; export ty ...

Angular React Form: Issue locating control within deeply nested FormArray structure

I am currently developing a nested, dynamic form where users can create groups and nest conditions within those groups or add new group objects within a `group` FormArray. The UI prototype is still under development, with some pieces not fully functional y ...