【发布时间】:2018-09-26 08:54:20
【问题描述】:
我正在使用 Angular 5 实现文件上传服务,我想给用户一些关于上传进度的反馈。我发现有几页建议使用 Angulars HttpClient 附带的 reportProgress 参数,但我无法让它工作。
我对所有的 http 请求都使用了一个包装类,然后它会执行一些逻辑,最后所有请求都以被调用的相同方法结束:
public request(request: HttpRequest<any>, options?: any): Observable<any> {
return this.httpClient.request(request.method, request.url, {
body: request.body,
headers: request.headers,
responseType: request.responseType,
...options
});
}
然后我将一个上传(发布)调用传递给它,{ reportProgress: true } 为 options。这根本不起作用,请求没有任何改变。所以我怀疑,我实际上需要在 HttpRequest 构造函数中使用reportProgress-参数来使其工作并相应地更改我的代码:
public request(request: HttpRequest<any>, options?: any): Observable<any> {
return this.httpClient.request(
new HttpRequest(request.method, request.url, request.body, {
headers: request.headers,
responseType: request.responseType,
...options
})
);
}
这导致了更奇怪的行为,现在无论我的选项是什么样的,我总是只收到 {type: 0} 作为请求的响应。
我在监督什么?我使用 Angular 5.1.1,我现在真的有点困惑。
举个明确的例子,现在我收到了这两个 HttpRequest 的相同响应:
{
"url":"http://127.0.0.1:8888/test",
"body":{
"data":"testdata"
},
"reportProgress":false,
"withCredentials":false,
"responseType":"json",
"method":"POST",
"headers":{ some-headers ... }
}
这个请求:
{
"url":"http://127.0.0.1:8888/api/pages",
"body":{
"pageUrl":"http://localhost:1234/"
},
"reportProgress":true,
"withCredentials":false,
"responseType":"json",
"method":"POST",
"headers":{ some-headers ... }
}
【问题讨论】:
-
你为什么使用包装类而不是interceptor?另请注意,
.clone方法可能是基于现有请求创建新请求的更好方法。 -
因为包装器已经写了一段时间了,还没有时间重写它。我知道
.clone()-方法,但想要一种通用方法,我不必检查选项对象中的单个属性。
标签: angular file-upload httprequest angular-httpclient