Angular 12 - Issue: None of the available overloads match this call. Overload 1 out of 5

Here is the code snippet I am working with:

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { BehaviorSubject } from 'rxjs';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  isAuth$ = new BehaviorSubject<boolean>(false);
  token!: string ; 
  userId!: string;

  constructor(private router: Router,
    private http: HttpClient) { }


  createNewUser(email: string, password: string) {
    return new Promise<void>((resolve, reject) => {
      this.http.post(
        'http://localhost:3000/api/auth/signup',
        { email: email, password: password })
        .subscribe(
          () => {
            this.login(email, password).then(
              () => {
                resolve();
              }
            ).catch(
              (error) => {
                reject(error);
              }
            );
          },
          (error) => {
            reject(error);
          }
        );
    });
  }

  login(email: string, password: string) {
    return new Promise<void>((resolve, reject) => {
      this.http.post(
        'http://localhost:3000/api/auth/login',
        { email: email, password: password })
        .subscribe(
          (authData: { token: string, userId: string }) => {  
            this.token = authData.token;
            this.userId = authData.userId;
            this.isAuth$.next(true);
            resolve();
          },
          (error) => {
            reject(error);
          }
        );
    });
  }

  logout() {
    this.isAuth$.next(false);
    this.userId = null!;
    this.token = null!;
  }
}

Error description:

No overload matches this call. Overload 1 of 5, '(next: null, error: (error: any) => void, complete?: () => void): Subscription', gave the following error. Argument of type '(authData: { token: string; userId: string;}) => void' is not assignable to parameter of type 'null'. Overload 2 of 5, '(next?: (value: Object) => void, error?: (error: any) => void, complete?: () => void): Subscription', gave the following error. Argument of type '(authData: { token: string; userId: string;}) => void' is not assignable to parameter of type '(value: Object) => void'. Types of parameters 'authData' and 'value' are incompatible. The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? Type 'Object' is missing the following properties from type '{ token: string; userId: string; }': token, userId

View my code here

Description of the error can be found here

Answer №1

To receive the expected response data type for this.http.post, you need to specify it.

Method 1: Specify it as

{ token: string, userId: string }

login(email: string, password: string) {
    return new Promise<void>((resolve, reject) => {
      this.http.post<{ token: string, userId: string }>(
        'http://localhost:3000/api/auth/login',
        { email: email, password: password })
        .subscribe(
          (authData: { token: string, userId: string }) => { 
            this.token = authData.token;
            this.userId = authData.userId;
            this.isAuth$.next(true);
            resolve();
          },
          (error) => {
            reject(error);
          }
        );
    });
  }

Method 2: Specify it as any

login(email: string, password: string) {
    return new Promise<void>((resolve, reject) => {
      this.http.post<any>(
        'http://localhost:3000/api/auth/login',
        { email: email, password: password })
        .subscribe(
          (authData: { token: string, userId: string }) => { 
            this.token = authData.token;
            this.userId = authData.userId;
            this.isAuth$.next(true);
            resolve();
          },
          (error) => {
            reject(error);
          }
        );
    });
  }

Answer №2

If you want to modify the generic type of the this.http.post function, you can set it to

{ token: string, userId: string }
as shown below:

this.http.post<{ token: string, userId: string }>(......);

However, I recommend using Observable directly instead of using promises and subscriptions within your function.

You can implement this approach like so:

  login(email: string, password: string): Observable<void> {
    return this.http
      .post<{ token: string; userId: string }>(
        "http://localhost:3000/api/auth/login",
        {
          email: email,
          password: password,
        }
      )
      .pipe(
        map((authData) => {
          this.token = authData.token;
          this.userId = authData.userId;
          this.isAuth$.next(true);
        })
      );
  }

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

enigmatic issue arising in Angular/Node

Could someone please shed some light on what might be causing the issue in my code? Thank you in advance! webpack: Compilation Failed. My Angular CLI: 1.6.3 Node: 8.9.4 OS: Windows 32-bit Angular: 5.2.1 Error Message: ERROR in ./node_modules/css-loader ...

What causes the lack of impact on lambda rendering speed despite integrating webpack?

Hey there, I've been working on implementing webpack for a project that involves microservices, Node.js, TypeScript, AWS, and AWS SAM. My main objectives are: Reduce the cold start time of lambda functions. Minimize security vulnerabilities by e ...

On iOS devices, the confirm/cancel alert box in Ionic v3 does not display in the center as expected

Encountering an issue with Ionic v3 where the alert box appears at the top only when a text box is included within it. This behavior is observed on regular devices like iPhones, but functions correctly on Android devices. Other form elements like checkboxe ...

What is the best way to set up TSLint to apply specific rules with one line and different rules with another line

There is a unique method in which I can specify the code to format, such as forcing the else statement to be on the same line as the ending brace of an if statement. "one-line": [ true, "check-open-brace", "check-catch", "check-else", "check-fin ...

What is the best method for dynamically compiling components in Angular 11?

Within our application, we have implemented a directive that allows for the dynamic display of Angular components: import {Compiler, Component, Directive, Input, ModuleWithComponentFactories, NgModule, OnDestroy, ViewContainerRef} from '@angular/core& ...

defining data types based on specific conditions within an object {typescript}

Can someone help with implementing conditional function typing in an object? let obj = { function myfunc (input: string): number; function myfunc (input: number): string; myfunc: function (input: string|number):string|number { ... } } I've been ...

child component in Angular 2 not receiving input data

My situation involves transmitting an event with data from one child component to another in the same parent. Essentially, this communication is happening between sibling components. This is how the code appears: Child Component A @Output() makeIsrCall ...

A guide on implementing RxJS Observables to target a specific DIV element

Currently, I am working with Angular 2. At the moment, I have been using this method to select a specific DIV element: <div #aaa> </div> @ViewChild('aaa') private aaa: ElementRef; ngAfterViewInit() { let item = this.aaa.nativeEle ...

Angular 2+ integration with Font Awesome 5

I'm having trouble adding FontAwesome 5 to my Angular 2+ application. I came across this package - https://www.npmjs.com/package/@fortawesome/fontawesome Can you guide me on how and where to import this package? Should I do it in the app.module.ts fil ...

Generating unit tests for an existing Angular2 application using Jasmine Karma can be a crucial step in ensuring the

I recently joined a development team working on an Angular2 application that requires all unit tests to be written using the Jasmine framework. I'm curious if there is a tool available that can automatically generate spec files for each class, providi ...

A guide to troubleshooting and resolving the elusive 500 Server Error in Next JS API

Currently, I am in the process of developing a chat bot using the innovative OPEN AI GPT 4 Model within NextJS. However, upon sending a POST request to http://localhost:3001/api/generate, I am faced with a Response displaying a status code of 500 along wit ...

Xcode 12.4 error: 'Notifications cannot be enabled' in Ionic 5

Since the Xcode 12.4 update, the Firebase Push Notifications have ceased functioning properly, displaying the error message "Notifications are not allowed for this application". I have made sure to update all Ionic, Angular, and Capacitor packages to the ...

Trouble seeing span in ion-item in Ionic 2: How can I display plain text instead?

It seems like I may be overlooking something, as I am experiencing an issue with adding a span to an Ion Item, where the span is not being rendered, nor is the div. <ion-card> <ion-card-title> </ion-card-title> <div> < ...

Angular Update Component on Input ChangeEnsuring that the component is automatically

<div class=" card-body"> <div class="row"> <div class=" font-icon-list col-lg-2 col-md-3 col-sm-4 col-xs-6 col-xs-6" routerLinkActive="active" *ngFor="let subject of subjects"> <div class=" fon ...

Any ideas for handling ProtractorJS timeouts while clicking an element?

The Issue at Hand I am currently facing a challenge with clicking a straightforward 'New Booking' button in my Angular 5 Material 2 Application. The code snippet for the button is as follows: <button _ngcontent-c9="" class="mat-menu-item" ma ...

MongoDB table collections (table names in other databases)

After setting up my express server to connect to mongodb, I encountered an issue despite everything working fine initially. I created a collection in my mongodb called projects (plural form). In my project.model.js file, I defined the model as follows: c ...

Toggle the visibility of a checkbox based on the JSON data

I have 4 check boxes that need to be dynamically displayed based on the value retrieved from my JSON. The JSON will only contain one checkbox name, and that specific checkbox should be shown to the user as checked. How can I achieve this functionality? Bel ...

NestJS RabbitMQ Microservice Integration

Currently, I am attempting to establish a connection to a Rabbit MQ docker container through NestJS microservice. The setup involves running it using vagrant. Unfortunately, I keep encountering the following error: [1601171008162] ERROR (32761 on local): D ...

The ion-list will only load image URLs once the height has been established

I've been dealing with a technical issue that I don't have much experience in, and I'm struggling to find a solution. While I now understand the root cause of the problem, I am unsure how to resolve it. The webpage I am working on sends a r ...

An issue occurred during the construction of an angular project: The Tuple type '[]' with a length of '0' does not contain any elements at index '0'

When I run the command ng build --prod, I encounter the following error: ERROR in src/app/inventory/inv-parts-main-table/dialog-component/dialog-component.component.html(5,16): Tuple type '[]' of length '0' has no element at index &apo ...