Angular-NGRX: Catch HTTP Error in the component

Viewed 284

I have implemented the store to my angular project , I'm able to catch and process the successSelector but no data is caught with errorSelector on HTTP error from backend.

catching the error in effects.ts as 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 }))
        )
    );
    
}

errorSelector is declared as below in selector.ts

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

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 dispatching of the service 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' ) {
          //console.log("response:", response);
            // Business actions
        
        }
        else {
        }
  
      }
    },  error => {
      
      this.errorMsg = error.error.Message;
   
    },
    () => {
      console.log('POST upload  - now completed.');
    })
    
  }

when ever the status is 200 from server,the response is caught, but when there is an error response it is not caught.

Please suggest how to catch httpError response and process it to UI.

1 Answers

You can remove all catchErrors that you placed after server calls.

  1. Use a intereptor to handle HTTP errors.

  2. Use (error) => {} after (response) => {} to process error in components.

Also you don't need that pipe to map response. Use it like:

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

And in your component:

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