Angular 5-Api Swaggerbody反应类型blob



我有一个应用程序,它调用一个返回文件并将其压缩为zip文件的api。

我创建了自己的服务,它运行得很好。

return this.http.get(this.rootUrl + '/api/Files/DownloadFile?files=' + fileSelected + '&user=' + user, { responseType: 'blob' as 'json' }); // working ok

这里的api响应是一个blob对象,因为它必须是

但是,当我尝试使用招摇过市生成的服务来做同样的事情时,它已经不起作用了。

let req = new HttpRequest<any>(
'GET',
this.rootUrl + `/api/Files/DownloadFile`, 
__body, 
{
headers: __headers,
params: __params,
responseType: 'text'
}
); // not working ok

该服务返回me null,但是在chrome检查器中,在对api调用的响应中,它显示了奇怪的字符。

this.filesService.DownloadFile({"files": ids, "user": this.user}).subscribe(
data => {
console.log(data); // data value is null but in the response I see strange characters
},
err => { 
console.log(err);
}
);

这是正常的,因为swagger服务的responseType是"text",我试图手动将contentType更改为"blob"(swagger规范(或"blob as json"(angular 5(,但效果不佳。

是否可以使用swagger生成的服务从Angular解决问题,或者我必须接触API?谢谢

您可以使用HttpInterceptor来更正请求的responseType。例如,对于返回媒体类型"应用程序/八位位组流"的服务功能:

import {Injectable} from '@angular/core';
import {
HttpEvent, HttpInterceptor, HttpHandler, HttpRequest
} from '@angular/common/http';
import {Observable} from 'rxjs';
@Injectable()
export class FileDownloadHttpInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
if (req.headers.get('Accept') === 'application/octet-stream') {
// @ts-ignore: ignore that responseType is read only
req.responseType = 'blob';
}
return next.handle(req);
}
}

然后在适当的模块中提供拦截器,例如app.module.ts:

providers: [{
provide: HTTP_INTERCEPTORS, useClass: FileDownloadHttpInterceptor, multi: true
}]

最后的步骤取决于您的服务到底返回了什么。对我来说,从服务中为HttpResponse调用window.open(response.url);就足够了,但也许您必须先将响应转换为blob,然后将blob转换为URL,请参阅如何下载Angular2或更高版本的文件。

第页。S.:用HttpInterceptors处理请求肯定不是最好的编码方式。服务生成方面的解决方案会更可取。但我发现在服务的den OpenApi描述中不可能指定responseType,并且生成的服务不够智能,无法根据声明的服务返回类型更改其默认json响应类型(或者我不够智能,不能适当配置生成器(。

最新更新