类型'HttpRequest <formdata>'的参数不能分配给类型'string |的参数。请求'

时间:2018-11-09 10:05:45

标签: angular angular-httpclient

我正在尝试以这种方式向http客户端发布文件

const req = new HttpRequest('POST', this.API, formData, { reportProgress: true });

        this.http.request(req).subscribe(event => {
            if (event.type === HttpEventType.UploadProgress) {...}

但打字稿会向我显示警告

Argument of type 'HttpRequest<FormData>' is not assignable to parameter of type 'string | Request'.
Type 'HttpRequest<FormData>' is not assignable to type 'Request'.
    Property 'contentType' is missing in type 'HttpRequest<FormData>'.

执行后,我在控制台中看到error

Error: First argument must be a url string or Request instance.

而根据angular的http.request定义,第一个参数可以是string或类型为Request

(method) Http.request(url: string | Request, options?: RequestOptionsArgs): Observable<Response>

我也不了解属性contentType缺少警告,这是否意味着我必须在标头中明确包含它?

我在这里做错什么了吗?

编辑:我正在使用

"@angular/common": "6.0.0",
"@angular/http": "6.0.0",

1 个答案:

答案 0 :(得分:2)

从错误消息中,您似乎使用的是 Http 而不是 HttpClient 。尝试从Http更改为HttpClient,然后检查是否适合您。

不要忘记将HttpClientModule添加到imports的{​​{1}}数组中。

@NgModule的{​​{1}}方法,用于接受类型为Http的请求。另一方面,request的{​​{1}}方法接受 HttpRequest

类型的请求