"Troubleshooting Typecscript and Angular: Dealing with mismatched argument

How can I resolve this Angular error:

(response: HttpResponse<User>) => {

which results in the following error message:

Argument of type '(response: HttpResponse<User>) => void' is not assignable to parameter of type '(value: HttpResponse<User> | HttpErrorResponse) => void'.
  Types of parameters 'response' and 'value' are incompatible.
    Type 'HttpResponse<User> | HttpErrorResponse' is not assignable to type 'HttpResponse<User>'.
      Type 'HttpErrorResponse' is missing the following properties from type 'HttpResponse<User>': body, clone

ALSO

(response.body); raises the following error:

Argument of type 'User | null' is not assignable to parameter of type 'User'.
  Type 'null' is not assignable to type 'User'.

I am currently using TypeScript 4.5.5 in my Angular project.

The function causing the issue is:

public onLogin(user: User): void{
    console.log(user)
    this.subscriptions.push(
      this.authenticationService.login(user).subscribe(
        (response: HttpResponse<User>) => {
          const token: string = response.headers.get(HeaderType.JWT_TOKEN) || '';
          this.authenticationService.saveToken(token);
          this.authenticationService.addUserToLocalCache(response.body);
          this.router.navigateByUrl('/dashboard');
        },
        (error: HttpErrorResponse) => {
          console.log(error);
          this.sendErrorNotification(NotificationType.ERROR, error.error.message);
        }
      )
    );
  }

NOTE: This function worked without issues in a previous project with a different version of TypeScript.

Answer №1

Issue 1

My observation regarding the login function in the AuthenticationService is that you are returning

Observable<HttpResponse<User> | HttpErrorResponse>
, as shown in the code snippet below:

login(user: User) {
  return (
    this.httpClient
      .post<HttpResponse<User>>(/* Login API url */, user)
      .pipe(catchError((err) => this.handleError(err)))
  );
}

handleError(err: HttpErrorResponse) {
  return of(err);
}

Solution for Issue 1

In order to properly handle and return errors within an Observable for subsequent subscriptions, it is recommended to use (rxjs) throwError:

import { throwError } from 'rxjs';

login(user: User) {
  return (
    this.httpClient
      .post<HttpResponse<User>>(/* Login API url */, user)
      .pipe(catchError((err) => this.handleAndThrowError(err)))
  );
}

handleAndThrowError(err: HttpErrorResponse) {
  return throwError(err);
}

Issue 2

Regarding HttpResponse<T>,

class HttpResponse<T> extends HttpResponseBase {
  constructor(init: { body?: T; headers?: HttpHeaders; status?: number; statusText?: string; url?: string; } = {})
  body: T | null

  ...
}

The value of response.body can potentially be null.


Solution for Issue 2

To handle the possibility of null for response.body, you can include a null check like so:

if (response.body)
  this.authenticationService.addUserToLocalCache(response.body);

Check out a Sample Demo on StackBlitz (featuring multiple scenarios)

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

Using Angular 8 for Filtering Firebase Data

I need to implement a filter on the titles of my stored data, but I am facing an issue where the structure of the filtered data changes. The original "key" of the data gets deleted by the filter and is replaced with an index instead. Link to repository : ...

Encountering an issue with NgRx store where the property 'products' is not recognized on the type 'ActionCreatorProps<{ payload: Product[]; }>' while attempting to build a reducer

Currently, I am delving into the @ngRx/store package within my Angular 14 App. My primary goal is to establish a basic store capable of containing a simple object Array. Here is an excerpt from my action file: import { Product } from 'src/app/data-mod ...

Showing a dynamically updated array in Angular

Within my Angular Application I am utilizing an ngFor loop in the component to display an array. Now, I am filtering the data from the array and aiming to update the newly filtered array in place of the original one. While I can successfully display the ...

Modify the animation attribute of the <circle> element using AngularJS

A new feature I implemented in my web app is a customizable countdown timer. As an added visual enhancement, I am now looking to create an animated circle around the timer. The animation duration will vary based on the countdown length. Here is a snippet ...

Quick + Vue Router - Lazy Loading Modules

For my personal project, I am using Vite alongside Vue 3 and have integrated vue-router@4 for managing routes. Since all of my modules share the same set of routes, I created a helper function: import { RouteRecordRaw } from 'vue-router' import p ...

"Troubleshooting issues with data loading using React's useEffect function

While working on my project, I encountered a strange issue where the isLoading state is being set to false before the data fetching process is completed. I am using the useEffect hook to show a loading spinner while fetching data from an API, and then disp ...

Removing Bootstrap Styles in Angular Single Page Applications

Currently, I am in the process of customizing the styles for an ASP.Net Core 2.2 Angular SPA. Upon examination, I noticed that a specific file webpack:///./node_modules/bootstrap/scss/_reboot.scss is being generated at runtime. To take control of the styl ...

Displaying multiple lines of text in a MatSnackbar in Angular is possible

For instance: let message: example;let message2 : example3; For Example: alert(message + '\n'+ message2); Is it possible to display the mat snackbar in Angular in a similar way as shown above?                     ...

Angular2 - a customizable dynamic popup feature

Currently, I am learning c# and Angular with the intention of creating a detailed modal popup that will appear when a user clicks on a div element. I would prefer to pass the detail data directly from the ngFor loop into the popup window if possible. If n ...

Merging multiple observables with RxJs forkJoin

UPDATE : I'm currently facing a challenging issue that I can't seem to resolve. Within my code, there is a list of objects where I need to execute 3 requests sequentially for each object, but these requests can run in parallel for different obje ...

The Router.url function consistently returns a forward slash instead of the actual current URL

I'm puzzled as to why, in this scenario, my current URL shows '/' when I refresh the page on '/component'. Shouldn't it show '/component' instead? However, the URL appears correct in the this.router array... Here ...

Applying the power of Angular function binding within .html() function in d3 visualizations

I am attempting to create a clickable d3 foreignObject span that triggers a function in the component TypeScript file. Below is a snippet of the code I have been working on: .append("foreignObject") .attr("x", x) .attr("y" ...

Angular 2 Quickstart encountered a 404 error when trying to retrieve the /app/main.js

I'm attempting to follow the Angular 2 quickstart guide, but I'm having trouble getting it to work. I've searched for similar questions but haven't found a solution yet. Can anyone assist me with this? Here is my code: app.component.t ...

Mistakenly importing the incorrect version of Angular

While working on my Angular 1 app in typescript, I faced an issue when importing angular using the following syntax: import * as angular from 'angular'; Instead of importing angular from angular, it was being imported from angular-mocks. Thi ...

Angular makes it easy to extract multiple parameters from a URL

In the process of developing a basic Angular application using TypeScript, I have encountered an issue. Within my project, there is a URL structure like this: www.example.com/api/1/countries/Italy/ My goal is to extract the values 1 and Italy from this U ...

Tips for verifying the Reactive formControl/formArray when submitting

In my scenario, I am working with a FormGroup titled Parent, which includes a FormArray as a control. This FormArray consists of another FormGroup referred to as the Child. Main Goal The main objective here is to perform validation on all controls of a sp ...

Creating a dynamic form in Angular based on user input

I am in the process of creating a dynamic web form where the user's input will determine the subsequent form inputs that are generated. For example: <mat-form-field> <mat-select placeholder="Type" [(ngModel)]="row.Type" (change)="Typ ...

Using Angular frontend to access Django Admin

Is it possible to integrate Django admin with an Angular frontend? I'm currently using Angular version 8.0 for the frontend and Django for the backend. In my urls.py file, I have added the admin as shown below: from django.urls import path, re_path f ...

Retrieving results from PostgreSQL database using pagination technique

When I'm pagination querying my data from a PostgreSQL database, each request involves fetching the data in this manner: let lastNArticles: Article[] = await Article.findAll({ limit: +req.body.count * +req.body.page, or ...

How to assign ngModel to a nested component in Angular?

If I have a component called InputComponent, which implements the ControlValueAccessor interface. Now, another component named AnotherComponent uses the InputComponent like this: <my-input [(ngModel)]="text"></my-input> While testing AnotherC ...