Where and how to use HttpResponse in angular2
Asked Answered
S

2

8

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());
Soleure answered 21/11, 2017 at 9:10 Comment(3)
when we are using HttpClient module you need not convert to json. The response is by default converted to jsonRochelrochell
Did you try these docs angular.io/guide/http ? Can you post more code from you http callElfont
@Elfont : updated!Soleure
R
11

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;
      }
    });
  }
}
Rictus answered 21/11, 2017 at 9:37 Comment(0)
P
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);
                 })
           )  
Punctuate answered 7/6, 2023 at 11:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.