【问题标题】:Angular 4 Http req, get text body from HttpResponseAngular 4 Http req,从 HttpResponse 获取文本正文
【发布时间】:2018-09-28 16:59:50
【问题描述】:

我正在使用 Spring Boot 开发 Angular 4 应用程序。基本上现在我有一项服务可以将文件从我的 Angular 应用程序上传到我的 Spring Boot 服务器。

我想在 Angular 日志中打印我从 Spring 收到的来自 ResponseEntity 对象的消息,但我不知道如何使用事件对象来获取消息,这是我的代码示例:

EDIT1: console.log(event.body) 可以很好地打印 message1message2,但我需要将 event.body 作为字符串才能在特定函数中使用它。

现在是HttpResponse<{}>.body: {},但我不知道它在 TS 中的含义以及如何将其转换为字符串。

EDIT2:我觉得应该是这样的

if(event.body instanceof String) function(event.body); 

但我仍然得到字符串和字符串之间的类型冲突。并将其修改为string,它表示“字符串”在此处用作值。

上传服务:

uploadFile(file: File): Observable<HttpEvent<{}>> {
    let formdata: FormData = new FormData();
    formdata.append('file', file);
    const req = new HttpRequest('POST', '/post', formdata, {
      reportProgress: true,
      responseType: 'text'
    });
    return this.http.request(req);
  }

上传方式:

 this.uploadService.uploadFile(file).subscribe(event => {
          if (event.type === HttpEventType.UploadProgress) {
            //Do some stuff
          } else if (event instanceof HttpResponse) {
            //message = event.body ?? //How to get message 1 or 2 below??? 
            console.log(message)
            });
            console.log('File ' + file.name + ' is completely uploaded!');
          }
        });

这是我的 Spring Boot 服务器的响应:

return ResponseEntity.status(HttpStatus.OK).body("message1");

或:

return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body("message2");

【问题讨论】:

  • 尝试 event.body了吗?您可以查看该对象的 API 文档:angular.io/api/common/http/HttpResponse
  • 是的,但是 event.body 没有返回一个字符串,我需要它作为一个字符串,以便稍后在材料小吃店中使用。
  • 嗯...它返回了什么?请给minimal reproducible example
  • 我做了一些修改。
  • new HttpRequest&lt;string&gt;(...) - 查看文档,他们向您展示了如何输入请求。

标签: spring angular spring-boot angular4-httpclient


【解决方案1】:

使用 String 构造函数有效:

String(event.body) 给我一个string,我可以在我的特定function(string) :void 中使用它

【讨论】:

    猜你喜欢
    • 2018-02-08
    • 1970-01-01
    • 2018-04-26
    • 2021-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-14
    • 2020-02-14
    相关资源
    最近更新 更多