【发布时间】:2018-09-28 16:59:50
【问题描述】:
我正在使用 Spring Boot 开发 Angular 4 应用程序。基本上现在我有一项服务可以将文件从我的 Angular 应用程序上传到我的 Spring Boot 服务器。
我想在 Angular 日志中打印我从 Spring 收到的来自 ResponseEntity 对象的消息,但我不知道如何使用事件对象来获取消息,这是我的代码示例:
EDIT1: console.log(event.body) 可以很好地打印 message1 或 message2,但我需要将 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<string>(...)- 查看文档,他们向您展示了如何输入请求。
标签: spring angular spring-boot angular4-httpclient