Angular HttpRequest检索部分响应

时间:2018-02-17 14:34:37

标签: angular typescript

我有一个请求,我上传文件并获得JSON响应。我想使用响应的一部分mysql> nopager 。我一直收到路径不存在的错误。

响应返回:

public delegate void show(string s);
namespace MyFunctions
{
    public class main
    {
        public static void SHOW(string str)
        {
            MessageBox.Show(str);
        }
    }
}

namespace xyz
{
    //use MyFunctions.main; // <--- something like that ??
    public class A : ProgramBase
    {
        public static event show show_event = MyFunctions.main.SHOW; // use delegate
        public void message()
        {
            show_event("Hi");
        }
    }
}

我尝试了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.

1 个答案:

答案 0 :(得分:1)

您需要输入正文或ersponse类型

解决方案#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(最干净的imho)

直接输入回复

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})
    }
  })