Angular HttpRequest 检索响应的一部分

生锈

我有一个请求,我在其中上传文件并获得 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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

仅隐藏 URL 的一部分 - Angular

一个组件是2个angular模块声明的一部分

让子组件知道它是父组件Angular的FormGroup的一部分

组件是Angular中2个模块的声明的一部分

Angular2:动态地使文本的一部分可点击

复制资源作为 Angular 9 库构建的一部分

Angular 2 @Component语法是ES6的一部分吗?

Angular 5 升级 - 模块构建失败:customPackage 不是编译输出的一部分

将字符串的一部分绑定到Angular作用域变量

Angular 5组件不是任何NgModule的一部分

Angular4 路由错误,因为组件不是任何模块的一部分

在 angular 5 中隐藏 ngFor 的一部分

您如何在Angular 5中获得URI的第一部分?

外部化.ts Angular文件。不应成为构建的一部分

如何在Angular中隐藏图表或div的一部分?

Angular.js指令以粗体显示一部分字符串

Angular + Electron基本应用程序不会刷新页面的一部分

Angular 5:为什么在调试模式下不显示“组件是 2 个模块声明的一部分”

Angular 6-检测变量何时在应用程序的另一部分中更改

类型X是2个模块的声明的一部分(Angular 2 RC5)

从BLOB格式实现PDF的预览或在网页中隐藏PDF的一部分-Angular

Angular 5中不断刷新DOM的一部分。尝试从YouTube API提取视频时

Ionic 4 / Angular 7应用程序*随机*不渲染组件的一部分(Android构建)

在 angular 中使用特定于域的服务作为公共服务的一部分的推荐方法是什么?

Angular HttpRequest不发送参数

仅检索文档的一部分

检索文件名的一部分

Angular-无法将响应分配给'request?类型:HttpRequest <any>

UIScrollView 的一部分不响应触摸