在angular2中何处以及如何使用HttpResponse

时间:2017-11-21 09:10:51

标签: angular angular-http

HttpResponse类(在 @ angular / common / http 中)是 @ angular / http 的类Response的替换(这是不建议使用)。查看文档并不太了解如何以及在何处使用它!此外,我试图替换我的旧角度代码,但由于这个类是通用的,所以它需要一个类型,例如HttpResponse<T>。给它类型给出错误:

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

任何人都可以帮我知道如何在角度中使用HttpResponse类吗?

更新

这是我的代码片段,我做的函数'get':

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

1 个答案:

答案 0 :(得分:4)

根据文档

HttpResponse

  

完整的HTTP响应,包括类型化的响应正文(如果未返回,则可以为null>。

     

HttpResponse是响应事件流中可用的HttpEvent

根据您所面临的具体问题 - T指的是适用于body HttpResponse属性的泛型类型。

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

因此,如果您的变量为res: HttpResponse<any>并且您尝试访问json属性,则res.json将失效,因为HttpResponse没有属性json 。您需要访问body,然后访问json

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

此外,使用HttpResponse的一个很好的例子是HttpInterceptor。拦截器拦截并更新响应和/或请求事件流。使用HttpResponseHttpRequest,您可以使用event instanceof检测要处理的流事件。

以下是拦截器的示例:

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