7

HttpResponse class(in @angular/common/http) is a replace of class Response of @angular/http(which is deprecated). Looking at docs don't give much idea of how and where to use it! Moreover, I tried to replace my old angular code but since this class is generic so it needs a type e.g. HttpResponse<T>. Giving it type gives an error as :

Property 'json' does not exist on type 'HttpResponse<any>'

Can anyone please help me know how to use HttpResponse class in angular?

UPDATE

This is my code snippet, a function 'get', that I made:

get(path: string, params: HttpParams = new HttpParams()): Observable<any> {
  return this.http.get(`${environment.api_url}${path}`, { headers: this.setHeaders(), search: params })
  .catch(this.formatErrors)
  .map((res: HttpResponse<any>) => res.json());
Ankur Shah
  • 801
  • 1
  • 12
  • 26

2 Answers2

10

HttpResponse as per docs is:

A full HTTP response, including a typed response body (which may be null >if one was not returned).

HttpResponse is a HttpEvent available on the response event stream.

As per your specific problem that you are facing - T refers to generic type which is meant for the body property of HttpResponse.

class HttpResponse<T> extends HttpResponseBase {
  constructor(init: {...})
  get body: T|null
  ...

So if your variable is res: HttpResponse<any> and you are trying to access json property like res.json will not work because HttpResponse doesn't have property json. You need to access body and then json.

(res:HttpResponse<any>) => console.log(res.body.json)

In addition, a good example where you use HttpResponse is HttpInterceptor. Interceptors intercepts and update the response and/or request event stream. And with HttpResponse and HttpRequest you can detect which stream event to handle using event instanceof.

Here is example of an interceptor:

@Injectable()
export class EmptyResponseInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const newReq = req.clone({
      responseType: 'text'
    });

    return next.handle(newReq).map((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse) {
        let newEvent: HttpEvent<any>;

        // alter response here. maybe do the following
        newEvent = event.clone({ 
          // alter event params here
        });
        
        return newEvent;
      }
    });
  }
}
Community
  • 1
  • 1
Hristo Enev
  • 2,421
  • 18
  • 29
0

Actually this answer is not working for me so I had to use solution like below.

return next.handle(changedReq)
           .pipe(
                 catchError((error: HttpErrorResponse) => {
                  if(error.status == 401 && error.statusText == "Unauthorized"){
                    this.jwtAuth.signout();
                  }
                    let errorMsg = '';
                    if (error.error instanceof ErrorEvent) {
                       console.log('This is client side error');
                       errorMsg = `Error: ${error.error.message}`;
                    } else {
                       console.log('This is server side error');
                       errorMsg = `Error Code: ${error.status},  Message: ${error.message}`;
                    }
                    console.log(errorMsg);
                    return throwError(errorMsg);
                 })
           )