Search code examples
angularobservableangular-httpclient

Cannot get response from HttpClient


I have been trying to handle an error response from my API.

What I'm trying to get:

dev tools showing expected error message

What I'm actually getting:

console log showing observable object

my service.ts:

import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';
import { map, catchError } from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';

private url = environment.urlServer;
constructor( private httpClient: HttpClient ) { }

guardarUsuario( data: {nombre: string, correo: string, pass: string, descripcion: string }) {
    return this.httpClient.post(`${ this.url }/usuario`, data).pipe(
        catchError((res: HttpErrorResponse) => {
            console.log(res);
            return throwError(JSON.stringify(res));
        
        })
    );
}

my component.ts:

this.coreService.guardarUsuario( data )
    .subscribe( res => {
            console.log('Successfull response: ', res);
        }, err => {
          console.log('Error response', err);
        }
    );

Update: Here´s the interceptor code

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { ToastrService } from 'ngx-toastr';

@Injectable({
  providedIn: 'root'
})
export class AuthInterceptorService implements HttpInterceptor {

  constructor(
    private toastr: ToastrService
  ) { }

  intercept( req: HttpRequest<any>, next: HttpHandler ): Observable<HttpEvent<any>> {
    const token: string = sessionStorage.getItem('token');

    let request = req;

    if ( token ) {
      request = req.clone({
        setHeaders: {
          'Authorization': `Bearer ${ token }`,
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Credentials': 'true'
        }
      });
    }
    return next.handle(request).pipe(
      catchError((err) => {
        if (err.status === 401) {
          this.toastr.error(`Error: ${ err }`)
        }
        throw throwError( 'Auth error: ', err );
      })
    );
  }
}

This is my first time working with interceptors, the interceptor its already imported in the providers of the app.module too. How can I get the error message from my API response in the error handler of my subscription?


Solution

  • If its any use to someone i changed the catchError of the interceptor from:

          catchError((err) => {
            if (err.status === 401) {
              this.toastr.error(`Error: ${ err }`)
            }
            throw throwError( 'Auth error: ', err );
          })
    

    to:

          catchError((error: HttpErrorResponse) => {
            let errorMsg = '';
            if (error.error instanceof ErrorEvent) {
              errorMsg = `Error ${ error.error.message}`;
            } else {
              errorMsg = `Error code: ${error.status}, Message: ${error.message}`
            }
            return throwError(errorMsg);
          })
    

    And the httpRequest to:

    guardarUsuario( data: {nombre: string, correo: string, pass: string, descripcion: string }) {
        return this.httpClient.post(`${ this.url }/usuario`, data);