Ank*_*hah 1 angular-http angular
HttpResponseclass(在@ angular / common / http中)是@ angular / http(不推荐使用)的类Response的替换。看文档并没有太多关于如何使用它的想法!此外,我试图替换旧的角度代码,但由于此类是通用的,因此需要类型,例如。赋予它类型将产生错误,如:HttpResponse<T>
Property 'json' does not exist on type 'HttpResponse<any>'
谁能帮我知道如何在Angular中使用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());
Run Code Online (Sandbox Code Playgroud)
根据文档的HttpResponse是:
完整的HTTP响应,包括类型化的响应主体(如果未返回,则可以为null)。
HttpResponse是HttpEvent在响应事件流可用。
根据您所面临的特定问题- T指代泛型类型,该类型适用于的body属性HttpResponse。
class HttpResponse<T> extends HttpResponseBase {
constructor(init: {...})
get body: T|null
...
Run Code Online (Sandbox Code Playgroud)
因此,如果您的变量是,res: HttpResponse<any>并且您尝试访问json属性,则该属性res.json将不起作用,因为HttpResponse没有属性json。您需要访问body然后json。
(res:HttpResponse<any>) => console.log(res.body.json)
Run Code Online (Sandbox Code Playgroud)
另外,使用的一个很好的示例HttpResponse是HttpInterceptor。拦截器拦截并更新响应和/或请求事件流。通过HttpResponse和,HttpRequest您可以检测到要处理的流事件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;
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4905 次 |
| 最近记录: |