我正在使用Spring Boot开发Angular 4应用程序。基本上现在我有一个服务,可以将文件从我的 Angular 应用程序上传到我的 Spring Boot 服务器。
我想在 Angular 日志中打印来自我从 Spring 收到的 ResponseEntity
对象的消息,但我不知道如何使用事件对象来获取消息,这是我的代码示例:
EDIT1:console.log(event.body)
打印message1
或message2
,但我需要将event.body
作为字符串才能在特定函数中使用它。
现在它HttpResponse<{}>.body: {}
但我不知道它在 TS 中是什么意思以及如何将其转换为字符串。
编辑2:我认为应该是这样的
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 引导服务器的响应:
return ResponseEntity.status(HttpStatus.OK).body("message1");
或:
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body("message2");
使用字符串构造函数工作:
String(event.body)
返回一个可以在我的特定function(string) :void
中使用的string