我有一个请求,我在其中上传文件并获得 JSON 响应。然后我想使用响应的一部分,即body.path
. 我不断收到路径不存在的错误。
响应返回:
{"success": 1, path: "somestring"}
我试过了e.body?.path
,但仍然没有运气。
let req = new HttpRequest('POST', globalVar.host + "/upload.php", formData, { responseType: "json", reportProgress: true});
this.http.request(req)
.subscribe(e=>{
if(e.type === HttpEventType.UploadProgress){
const percentDone = Math.round(100 * e.loaded / e.total);
this.uploadProgress = percentDone;
}
if(e.type == HttpEventType.Response){
this.fileLocation.emit({"path": e.body.path, "next": true})
}
})
随着e.body?.path
我得到在编译时这个错误。error TS1005: ':' expected.
和error TS1003: Identifier expected.
e.body.path
给出错误 error TS2339: Property 'path' does not exist on type '{}
您需要输入正文或响应类型
解决方案#1(最简单)
this.fileLocation.emit({"path": (e.body as any).path, "next": true})
解决方案#2
interface MyResponse
{
success: number;
path: string;
}
this.fileLocation.emit({"path": (e.body as MyResponse).path, "next": true})
解决方案#3(最干净的恕我直言)
直接输入回复
this.http.request(req)
.subscribe((e: HttpEvent<MyResponse> ) //<== type here
=>{
if(e.type === HttpEventType.UploadProgress){
const percentDone = Math.round(100 * e.loaded / e.total);
this.uploadProgress = percentDone;
}
if(e.type == HttpEventType.Response){
this.fileLocation.emit({"path": e.body.path, "next": true})
}
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句