在Angular的HttpClient类中使用request方法 [英] using the request method in Angular's HttpClient class

查看:199
本文介绍了在Angular的HttpClient类中使用request方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Angular 4中开发服务,该服务必须提供通用的http请求方法(而不是分开的get,put,post ...).我正在尝试使用HttpClient中的request方法,但无法管理传递必需的options参数.我的代码大致如下:

I'm developing a service in Angular 4 which must offer a generic http request method (instead of separated get, put, post ... ). I'm trying to use the request method in HttpClient, but I can't manage to pass the required options parameters. My code looks roughly like this:

let options = { 
    headers: headers,
    content: content,
    responseType: ????,
    observe: ??????
};

http.request(method, url, options)
     .map(res => new SeamResponse(res.status, res.json()))

现在,我遇到两个问题:

Now, I'm having two problems:

  1. 我无法传递reponseType选项,因为如果我指定"json"之类的值,则会出现以下错误:

错误TS2345:类型为'{headers的参数:HttpHeaders;内容:字符串; responseType:字符串; }'不可分配给类型为'{body ?: any;的参数;标头?:HttpHeaders; params ?: HttpParams;观察?:HttpObserve; reportProgress?:...'.属性"responseType"的类型不兼容.类型'string'不能分配给类型'"json" | "arraybuffer" | 斑点" | 文本"'.

error TS2345: Argument of type '{ headers: HttpHeaders; content: string; responseType: string; }' is not assignable to parameter of type '{ body?: any; headers?: HttpHeaders; params?: HttpParams; observe?: HttpObserve; reportProgress?:...'. Types of property 'responseType' are incompatible. Type 'string' is not assignable to type '"json" | "arraybuffer" | "blob" | "text"'.

  1. 我也不可以通过观察选项,因为它的类型显然不是从HttpClient类中导出的.

错误TS2305:模块'"/用户/pchacin/Documents/workspace/seam-sdk-core-ts/node_modules/@ angular/common/http"'没有导出的成员'HttpObserve'.

error TS2305: Module '"/Users/pchacin/Documents/workspace/seam-sdk-core-ts/node_modules/@angular/common/http"' has no exported member 'HttpObserve'.

  1. 我无法处理响应,因为它无法识别map方法,据我了解这是Observable的标准方法:

错误TS2339:类型可观察"上不存在属性地图".

error TS2339: Property 'map' does not exist on type 'Observable'.

非常感谢

问题2通过导出HttpObserve在最新版本的angular(4.4.1)中作为实验功能得到解决,但是关于github中有关该主题的讨论建议将HttpObserve类型删除,并将此选项定义为字符串,因此我不愿意走这条路.我的问题是:请求方法自4.2起已经存在一段时间了,至少没有人使用过吗?如果可以,怎么办?

Question 2 is solved in the latest version of angular (4.4.1) as an experiment feature by exporting HttpObserve, however discussions about the topic in github suggest the HttpObserve type will be removed and this option will be defined as string, so I'm not inclined to follow this path. The question I have is: the request method has been around for some time, since 4.2, at least Hasn't anyone used it ever? if so, how?

推荐答案

responseType 的错误与

It happens that the error with the responseType is related to an issue with TypeScript and literal string types. The proper way to specify it is:

let options = { 
    headers: headers,
    content: content,
    responseType: 'text' as 'tex',
    observe: 'response' as 'response'
 };

这篇关于在Angular的HttpClient类中使用request方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆