Where and how to use HttpResponse in angular2

Ankur Shah picture Ankur Shah · Nov 21, 2017 · Viewed 9.1k times · Source

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());

Answer

Hristo Enev picture Hristo Enev · Nov 21, 2017

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;
      }
    });
  }
}