Angular 可以通过 HttpResponse 类和 HttpClient 的 get() 方法来处理分块的 HTTP 响应。
示例代码如下:
import { HttpClient, HttpResponse } from '@angular/common/http';
// 发送分块响应的 HTTP 请求
this.httpClient.get('/chunked-response', {observe: 'response'})
.subscribe((response: HttpResponse) => {
// 如果响应的 isTruncated 属性为 true,则继续请求下一个分块
while (response.body.isTruncated) {
this.httpClient.get('/chunked-response', {
observe: 'response',
headers: {'Content-Range': `bytes=${response.body.nextByte}-${response.body.totalBytes - 1}`}
}).subscribe((nextResponse: HttpResponse) => {
// 将下一个分块的内容合并到当前响应的 body 中
response.body.content += nextResponse.body.content;
// 更新下一个分块的字节范围
response.body.nextByte = nextResponse.body.nextByte;
response.body.totalBytes = nextResponse.body.totalBytes;
// 如果当前响应的 isTruncated 属性为 false,则表示所有分块请求已完成
if (!nextResponse.body.isTruncated) {
console.log(response.body.content); // 打印完整响应内容
}
});
}
});
此示例中,首先使用 HttpClient 的 get() 方法请求分块响应。当响应返回后,检查 isTruncated 属性的值,如果为 true,表示响应被分成了多个块。接下来,通过 while 循环,使用 HttpClient 发送新的请求,每个请求的 Content-Range 请求头会指定该请求所请求的字节范围。每个分块的内容通过将其追加到当前响应的 body 属性中进行合并。当最后一个分块请求完成后,将得到完整的响应内容,并打印到控制台。