The presence of catchError() within the pipe() function will display an error specifically at the .subscribe stage

I encountered an issue while trying to handle errors for a method in Angular. After adding a catchError check using the .pipe() method, I noticed that the variable roomId was marked with a red squiggly line. The error message read:

TS2345: Argument of type 'unknown' is not assignable to parameter of type 'number'

This section shows where the error check is being performed.

this.firstRoom(room).pipe(
        first(), 
        catchError((error: HttpErrorResponse)=>{
             if(error.status != 200){
               // handle error
             }else{
               // return error
               return throwError(error);
            }
         }),

Below is the complete method.

public findRoom(room: Room): Observable<house> {
    return new Observable(house =>{
      this.firstRoom(room).pipe(
        first(), 
        catchError((error: HttpErrorResponse)=>{
                  if(error.status != 200){
                    // handle error
                  }else{
                    // return error
                    return throwError(error);
                  }
                }),
      ).subscribe(roomId => 
        this.goToThisRoom(roomId).pipe( <----- roomId throws that argument type unknown
          first()
        ).subscribe(roomInfo => {
            if (roomInfo.status === "failed") {
              house.next(house.failed);
            } else {
              this.downloadRoom(roomId).pipe(
                first()
              ).subscribe(blobFile =>
                this.getRoom(blobFile, name)
              );
              house.next(house.ready)
            }
          }
        )
      )
    });
  }

Do you have any insights into why this might be happening?

Answer №1

When using the <code>catchError method, it is important to remember that you need to return an observable as the result. This can either be done by throwing an error with throwError, or by returning a new observable if you have handled the error.

If you find yourself in a situation where you need to do this, you can follow the example below:

import { of } from 'rxjs';

...

catchError((error: HttpErrorResponse) => {
  if (error.status != 200) {
    // Here you can handle the error and provide any fallback value that you want to return.
    // This could be anything like a number, string, or object depending on your specific requirements.
    const fallbackValue: Room = { properties... };
    return of(fallbackValue); // This will be received in your subscription callback
  } else {
    // return the error
    return throwError(error);
  }
}),

Answer №2

  1. Avoid using the new Observable constructor within a subscription as it can make the logic difficult to follow and canceling pending operations becomes challenging.

  2. Ensure that // handle error actually handles errors.

A more structured approach could be:

public findRoom(room: Room): Observable < house > {
    return this.firstRoom(room).pipe(
        first(),
        catchError((error: HttpErrorResponse) => {
            if (error.status != 200) {
                return EMPTY;
            } else {
                // return error
                return throwError(error);
            }
        }),
        switchMap(roomId => this.goToThisRoom(roomId)),
        first(),
        // ... continue with the rest of the pipe
    );
}

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

Arranging a list of objects with a designated starting value to remain at the forefront

Consider the array and variable shown below: array = ['complete','in_progress','planned']; value = 'planned'; The goal is to always sort the array starting with the 'value' variable, resulting in: array ...

"Trouble with Bootstrap Collapse function - Utilizing ng-bootstrap, eliminating the need for JQuery

In my Angular 8 project, I have Bootstrap 4.3.1 and ng-bootstrap 5.1.1 integrated. As per the ng-bootstrap documentation, including ng-bootstrap in your project eliminates the need to manually add jQuery, as it is encapsulated by ng-bootstrap and not requ ...

Crafting a dynamic HTML template in Angular using template literals and the *ngFor directive

I've been developing a toast component that accepts HTML tags as strings. This requires me to iterate through the errorMsgs array below and dynamically build a list. However, I'm currently facing an issue where the *ngFor loop inside it is iterat ...

Tips for sending data from an HTML page to an Angular custom element

I have successfully created an angular custom element from an angular component that I would like to call from a standard HTML page. The custom element requires a parameter, which functions properly when called as a component within an angular project. Ho ...

Symfony using Vite with Vue 3 encounters an error: Uncaught ReferenceError - exports is undefined

Currently, I am in the process of developing a Symfony 3 Application with Vite and Vue3 integrated with TypeScript. To replace Symfony's Webpack Encore, I opted for the Vite Buildtool using this convenient plugin: https://github.com/lhapaipai/vite-bu ...

Using JavaScript to assign function arguments based on arbitrary object values

I am facing a challenge with a collection of arbitrary functions and a method that takes a function name along with an object or array of parameters to call the respective function. The issue arises from the varying number of inputs in these functions, som ...

Facing problem with Angular 7 when making a GET request for non-JSON data

Currently, I am retrieving JSON data from a URL using the following method: this.http.get('http://localhost:3200/mydata').subscribe(data => { console.log(data); }); The response is in JSON format, and everything seems to be working fine. ...

Tips for creating and obtaining content in a model-view-controller (MVC) project

I am facing a challenge with the connection between my ASP.NET MVC app's TypeScript and C# code. While I can see that the C# code is giving the response in the Inspect, the value is there but I am unsure how to handle it in TypeScript. C# Code: name ...

Discovering child elements within an iframe using Angular and customizing their appearance

Is there a simple and effective way to locate child nodes within an iframe using Angular in order to access the HTML element? Currently, I have implemented the following method: I designated a reference variable within my iframe (#privacyPolicy) <ifra ...

RxJs Subject: Acquiring the Sender

I have been working with Subjects and there is a .subscribe() in a specific class. Emitting values to this class from different other classes has resulted in the subscribe function being triggered multiple times, yet I am unsure of where these emits are co ...

How to transfer files between Dropbox and AWS S3 using Angular 5

Currently, I'm utilizing the Dropbox file picker to download a file. Once a file is selected using the Dropbox picker, I obtain the download link. I'm wondering if it's possible to save it as a bytestream in the browser and then upload it t ...

Establishing a connection between TypeScript and MongoDB

Whenever I try to add the mongo connection to the request, I encounter an error. The error message says: 'Property 'dbClient' does not exist on type 'Request<ParamsDictionary>'. I want the connection to be accessible witho ...

Apply a unique CSS class to the first two elements, then skip the following two elements, and continue this pattern using ngFor in Angular and flex styling

Here is a code snippet that displays a list of products using *ngFor in Angular: <div class="container-products"> <div class="item-product" *ngFor="let product of ['product A', 'product B', 'prod ...

Finding a way to reference multiple components within a mapping function

In order to set a ref to each project within the map function, I am trying to pass forwardRef from child to parent. At the moment, I am only able to get a single Project. However, I need to set refs to an array list so I can work with it. Below is what I h ...

Issue with ReactJS Typescript: Cannot assign type 'number' to type '0, 8, 16, 24, 32, 40, or undefined'

I am looking to implement a grid from material-ui in react using typescript. You can view the live demo here. I have made adjustments to the example to make it work with typescript. Here is how my demo.jsx file looks like: import { withStyles } from &apo ...

Looking for a way to detect changes in a select menu using Angular?

How can I determine with the openedChange event if there have been any changes to the select box items when the mat select panel is closed or opened? Currently, I am only able to detect if the panel is open or closed. I would like to be able to detect any ...

Error message: "ExpressionChangedAfterItHasBeenCheckedError in dynamic reactive forms"

This issue arises when utilizing nested reactive forms and the child component employs ng-if*. It's the template interpolation that leads to complications. You can refer to the reproduction here: https://plnkr.co/edit/GrvjN3sJ05RSNXiSY8lo //our root ...

AWS Alert: Mismatch in parameter type and schema type detected (Service: DynamoDb, Status Code: 400)

Upon trying to log into my development Angular system, I encountered the following error. My setup involves AWS Serverless, Amplify Cognito, and Graphql. An error occurred: One or more parameter values were invalid. Condition parameter type does not ma ...

Steps to activate or deactivate a button in Angular 2 depending on required and non-required fields

I am looking to have the Save button activated when the Placeholder value is set to 'Optional'. If the value is set to 'Mandatory', then the Save button should be deactivated and only become active if I input a value for that field. He ...

Steps for setting up an auth guard:1. Define a

I am facing an issue with implementing two guards in my Angular application. The first guard is supposed to restrict unauthorized users from accessing certain pages, while the second guard is meant to prevent authorized users from accessing the "sign-in" a ...