Handling HTTP Errors in Angular Components with NGRX

I have successfully integrated the store into my angular project. I am able to handle and process the successSelector, but I am facing difficulty in capturing any data with the errorSelector when an HTTP error occurs from the backend.

The error is being caught in effects.ts as shown below:

    private postupload() {
    return this.actions$.pipe(
        ofType(uploadActionTypes.uploadRequestAction),
        map(action => action.fileUpload),
        switchMap((fileUpload: any) => this.uploadService.postUploadfile(fileUpload)),
        map((data: any) => uploadActionTypes.uploadSuccessAction({ data })),
        catchError((error: any) => of(uploadActionTypes.uploadFailureAction({ error }))
        )
    );
    
}

The errorSelector is defined as follows in selector.ts:

export const uploadErrorSelector = createSelector(
uploadStateSelector,
(state: IuploadState) => state.uploadFileResponse.Errors
);

In Service.ts:

  public postUploadfile(fileinfo: any): Observable<any> {

    let savefileUploadUrl = `${this.apiBaseURL + UploadApiEndPointUrl.fileUploadUrl}`;
    return this.http.post<any>(savefileUploadUrl, fileinfo).pipe(
      map((response: Response) => response),
      catchError(this.errorHandler)
   )
  }
     errorHandler(error: HttpErrorResponse) {
     return Observable.throw(error);
  }
  }

In component.ts, the service dispatching is called,

  postUploadFileSubscription() {
    this.postUploadFileSubscription$ = this.store.select(UploadSelector.uploadSelector).subscribe(
      response =>{
        console.log("response:", response);
      if(response.hasOwnProperty('Data')){
        if (typeof (response.Data) !== 'undefined' ) {
            // Business actions
        
        }
        else {
        }
  
      }
    },  error => {
      
      this.errorMsg = error.error.Message;
   
    },
    () => {
      console.log('POST upload  - now completed.');
    })
    
  }

When the server responds with a status code of 200, the response is captured. However, when there is an error response, it is not captured.

Please provide suggestions on how to capture and handle HTTP error responses for UI processing.

Answer №1

If you find yourself adding catchError after every server call, consider the following alternatives:

  1. Implement a custom HttpInterceptor to handle HTTP errors globally.

  2. Handle errors directly in components by using (error) => {} alongside (response) => {}.

Remove unnecessary pipe for mapping response data and simplify your code structure like this:

return this.http.post<Response>(savefileUploadUrl, fileinfo);

In your component, subscribe to state changes with error handling as needed:

this.store.select(UploadSelector.uploadSelector).subscribe((res) => {}, (err) => {});

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

Disabling a Field in Angular While Preserving its Value

Hey there, late night folks! I have a quick question about Angular. I'm working with a form that includes a specific field where I set the value using patchValue, but I also need to disable this field. The issue is that after disabling it, the value i ...

Tips for keeping your cool when a listener is suggesting changing it to a const variable

How can I output the isChecked value to the parent component? This value indicates whether the checkbox is clicked or not. Unfortunately, changing it to const is not an option due to an assignment below. My linter is suggesting that I change it to const, ...

TypeScript 1.6 warning: Component XXX cannot be instantiated or called as a JSX element

var CommentList = React.createClass({ render: function () { return ( <div className="commentList"> Hello there! I am the CommentList component. </div> ); } }); var ...

Encountering the error "Element implicitly has an 'any' type because expression of type 'string' cannot be used to index type '{}'" can be frustrating when working with React TypeScript

I'm encountering an issue when trying to access an object with an id in the code below. An error message stating 'Element implicitly has an 'any' type because expression of type 'string' can't be used to index type ' ...

Is there a way to view the type signature of the resulting intersection type (type C = A & B) in IDE hints, rather than just seeing the components?

When analyzing types defined by intersection in Typescript, I notice that the hint remains identical to the original definition: https://i.stack.imgur.com/mjvI8.png However, what I actually want is to visualize the resulting shape, similar to this: http ...

A guide on setting values within a FormBuilder array

I am facing an issue with setting array values in formBuilder.array. While it is easy to set values in a regular formBuilder, I am struggling to do the same in formBuilder.array. I have tried setting values for both 'listServiceFeature' and &apos ...

Running the Express service and Angular 6 app concurrently

Currently, I am in the process of developing a CRUD application using Angular6 with MSSQL. I have managed to retrieve data from my local database and set up the necessary routes, but I am encountering difficulties when it comes to displaying the data on th ...

I am looking to incorporate serial numbers into two distinct loops within an Angular application

I need help adding a serial number using two separate ngFor loops. Here is the code: <table> <tr> <th>Sr</th> <th>Name</th> </tr> <ng-container #atvalue> <tr *ngFor="let item of items; l ...

Ionic has been experiencing issues with inaccurate boolean results being generated by Angular typescript

I have created a random number generator that requires the user to input a maximum and minimum value to generate a random number within that range. The application will show an error under two conditions: If either of the numbers entered is negative If t ...

Display or conceal an icon based on the data in the field

Can someone provide guidance on how to make an icon appear or disappear based on the logic within [ngIf]? The icon should only be displayed if there is information in a specific field. Should I implement this inside ngIF or in my TS file? Can the icon cl ...

limitation on pairings of two generic types

How can I specify in TypeScript that "You can pass in any two objects, as long as their combination satisfies type X"? For example, consider the following function: function myFunction(options: {x: number, y: string}){ } Now, let's say we have anot ...

Looking for a SSR Component to Choose Dates?

In the process of designing a landing page, I encountered a challenge with incorporating a date picker feature. My goal is to have users select a date and then be redirected to another page upon clicking a button. The technology stack includes NextJS where ...

Is it possible for Typescript to allow extracted interfaces while excluding properties from another interface?

I've been searching for information on the specific features of this. Despite my efforts on Google, I have been unable to find the details. Any help would be greatly appreciated! interface Numbers { number: number; number2: number; number ...

Upgrade from Next.js version 12

Greetings to all! I have recently been assigned the task of migrating a project from next.js version 12 to the latest version. The changes in page routing and app routing are posing some challenges for me as I attempt to migrate the entire website. Is ther ...

Tips for incorporating custom logic into the redirectTo field in Angular

Can I implement custom logic with redirectTo in Angular? Consider the following routes defined using forRoot: const routes: Route[] = [ { path: ':companyId', canActivate: [CanActivateCompany], children: [ { path: '' ...

Having difficulty authenticating Slack requests

I'm currently working on a project to develop a Slack bot using the events API for an experiment at my job. I am facing challenges in verifying the request and can't seem to pinpoint where I'm making a mistake. The bot is being built using ...

Utilizing child component HTTP responses within a parent component in Angular: a comprehensive guide

As a newcomer to Angular, I find myself struggling with http requests in my application. The issue arises when I have component A responsible for retrieving a list of IDs that need to be accessed by multiple other components. In component B, I attempted t ...

Tips for effectively narrowing the `undefined` type

Why am I getting this error message? const func = (a: unknown) => { if (a && typeof a === 'object' && 'b' in a) { a.b; } }; The error message I'm receiving is: Property 'b' does not exist on ty ...

Adding an object to an array in Angular 7: A step-by-step guide

Why am I facing issues while pushing an object into an array? This is how I am attempting to do it: this.passData = this.tribeForm.value; var id = {"tribe_id": 1} this.passData.push(id) Shown below is the value in the tribeForm https://i.sstati ...

What is the best way to initiate the registration page through the @auth0/auth0-react library?

I've hit a roadblock in trying to automatically launch the sign-up (registration) page using @auth0/auth0-react. Previously, I would send mode which worked with auth0-js. So far, I have attempted the following without success: const { loginWithRedir ...