angular - 订阅 angular observable 是未定义的
问题描述
我对 Angular 很陌生,现在尝试上传文件,当文件上传成功时,它将在数据库中创建一个条目,其中包含 api 返回的数据。
对于我正在使用的上传
import { FileUploader } from 'ng2-file-upload';
这是我的上传功能:
uploadSingleFile() {
if (this.uploader.queue.length <= 0)
return;
const file = this.uploader.queue[0];
const fileItem = file._file;
const data = new FormData();
data.append('file', fileItem);
this.uploadFile(data, () => file.remove()).subscribe((image: any) => {
this.uploadedFile = image;
});
}
uploadFile(data: FormData, onSuccess: any): Observable<any> {
return this.fileService.upload(data, onSuccess, r => { console.error(r); });
}
fileService
看起来像:
upload(model: any, onSuccess: any = undefined, onError: any = undefined) {
return this.httpClient
.post(`${this.baseUrl}upload`, model, { observe: 'response' })
.pipe(
map((response: any) => {
console.log(response.status);
if (response.status === 201) { // this works, I'm getting Status 201
if (onSuccess !== undefined)
onSuccess(response);
}
else if (onError !== undefined)
onError(response);
})
);
}
调用的api函数:
[HttpPost, Route("upload")]
public async Task<ActionResult> Upload()
{
// ...
FileForUploadResponseDto fileForUploadDto = new FileForUploadResponseDto
{
FilePath = fileName,
CreationDate = DateTime.Now,
Title = file.FileName,
Size = fileLength
};
return StatusCode(201, fileForUploadDto);
}
它一直有效,直到这条线uploadSingleFile()
this.uploadFile(data, () => file.remove()).subscribe((image: any) => {
this.uploadedFile = image;
});
变量
image
未定义。任何的想法?我想在我的响应正文中发送数据。
解决方案
地图操作员总是在订阅之前工作。它根据需要提供重写 http 响应。您使用了“map”运算符但没有返回任何内容,因此订阅数据将为空。
upload(model: any, onSuccess: any = undefined, onError: any = undefined) {
return this.httpClient
.post(`${this.baseUrl}upload`, model, { observe: 'response' })
.pipe(
map((response: any) => {
console.log(response.status);
if (response.status === 201) { // this works, I'm getting Status 201
if (onSuccess !== undefined)
onSuccess(response);
}
else if (onError !== undefined)
onError(response);
return response.body; --> you should add this line.
})
);
}
推荐阅读
- node.js - 在mongodb nodejs中迭代更新对象数组
- java - 将分页库 3 与来自 Java 的 LiveData 一起使用
- python - 用户未进行身份验证
- arcore - ARCore 获取深度图像中的错误?
- javascript - NodeJS Axios:“监听器”参数必须是函数类型
- javascript - 打开图层检查功能是否在视口中
- autodesk-forge - 如何检查我们是否在设计自动化云上?
- java - 将 controlsfx 11.0.2 集成到 JavaFX 14.0.1
- python-3.x - 多维 Rosenbrock 函数的 Sympy 实现?
- javascript - 从 react-select 发送信息到 handleSubmit 函数