gpt4 book ai didi

angular - 从 Http 请求转换响应时出现问题

转载 作者:可可西里 更新时间:2023-11-01 16:35:40 32 4
gpt4 key购买 nike

我有这个 HTTP 请求:

storeCategory(file: File, category: CategoryModel): Observable<HttpEvent<{}>> {
const formdata: FormData = new FormData();
console.log("1")
formdata.append('file', file);
formdata.append('category', new Blob([JSON.stringify({ "category_name": category.category_name, "category_description": category.category_description })], { type: "application/json" }))
const url = `api/cateogry/saveCategory`;
const req = new HttpRequest('POST', url, formdata, {
reportProgress: true,
responseType: 'text'
});
return this.http.request<CategoryModel>(req);
}

我从这个方法发送数据和图像,我的后端方法返回一个 JSON 对象,但我想将该对象绑定(bind)为 CategoryModel,但现在它绑定(bind)到 HttpEvent

我的回调: enter image description here另一张图片: enter image description here

另一张图片: enter image description here

最佳答案

从您发布的图片来看,请求似乎不是 CategoryModel , 但列表 CategoryModelHttpResponse 里面-目的。由于您使用的是 http.request ,你会得到很多回复,每一个都有不同的HttpEventType found here .您需要过滤每种类型的响应,并根据类型获取您想要的内容(例如 event.type === HttpEventType.Response )。

试试这个:

storeCategory(file: File, category: CategoryModel): Observable<CategoryModel[]> {
const formdata: FormData = new FormData();
console.log("1")
formdata.append('file', file);
formdata.append('category', new Blob([JSON.stringify({ "category_name": category.category_name, "category_description": category.category_description })], { type: "application/json" }))
const url = `api/cateogry/saveCategory`;
const req = new HttpRequest('POST', url, formdata, {
reportProgress: true,
responseType: 'text'
});
return this.http.request<any>(req).pipe(map(event => {
console.log("event",event);
if(event.type == HttpEventType.Response){ // try different event types based on desired result.
event.body = event.body.replace(/\\/g,"/"); // replace all double backslashes with slash.
return <CategoryModel[]>JSON.parse(event.body); // try to parse the data if it is a string
}
}));
}

我将方法的返回类型更改为 Observable<CategoryModel[]> ,并更改返回语句以转换结果以反射(reflect)这一点。

记得给import {map} from 'rxjs/operators'在你的组件中记得import {HttpEventType} from '@angular/common/http'在你的组件中

并查看 Angular docs 中的示例

不同的HttpEventType可以查到here

关于angular - 从 Http 请求转换响应时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55061094/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com