[英]Ionic 4: when trying to upload selfie image, Error: Uncaught (in promise): TypeError: Cannot read property 'subscribe' of undefined
i am using ionic version 4. Trying to take picture from phone camera and upload.我正在使用离子版本 4。尝试从手机摄像头拍照并上传。 Last 2 days i am trying to solve this.
最近两天我试图解决这个问题。 Thanks in advance.
提前致谢。
const options: CameraOptions = {
quality: 50,
sourceType: sourceType,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
cameraDirection: this.camera.Direction.FRONT,
allowEdit: true,
targetHeight: 300,
targetWidth: 300,
}
this.camera.getPicture(options).then((imageData) => {
this.imageData = imageData;
this.service.postFile(url, this.imageData).subscribe(res => {
if (res.status == 200) {
this.toastr.presentToast('image done')
}
}, error => {
this.toastr.presentToast('image failure')
});
}
postFile(url, file: any): any {
const reader = new FileReader();
reader.onload = () => {
const formData = new FormData();
const imgBlob = new Blob([reader.result], {
type: file.type
});
formData.append('file', imgBlob, file.name);
reader.readAsArrayBuffer(file);
return this.http.post(environment.domain + url, formData).pipe(map(res => res),
catchError((err) => throwError(err))
);
}
} }
You are getting that error because you are calling a void method but you are expecting that it will return an observable.您收到该错误是因为您正在调用一个 void 方法,但您期望它会返回一个可观察的。
I suggest you create method to make the reader an observable and use flatmap on your postFile so that you will call the http method once it's done with reader observable.我建议您创建方法以使阅读器成为可观察的并在您的 postFile 上使用平面图,以便在完成阅读器可观察后调用 http 方法。 So you will be using the postFile method and it will return an observable now.
所以你将使用 postFile 方法,它现在会返回一个 observable。
I created a similar method just to show you the logic on how to do it properly.我创建了一个类似的方法,只是为了向您展示如何正确执行此操作的逻辑。 Please change it as per your needs.
请根据您的需要进行更改。
readFile(url, file: any) {
const res = new Subject<Blob>();
const reader = new FileReader();
reader.onload = () => {
const imgBlob = new Blob([reader.result], {
type: file.type
});
res.next(imgBlob);
res.complete();
reader.readAsArrayBuffer(file);
}
return res.asObservable();
}
postFile(url, file: any) {
return this.readFiles(url, file).pipe(
flatMap((imgBlob: Blob) => {
const formData = new FormData();
formData.append('file', imgBlob, file.name);
return this.http.post(environment.domain + url, formData).pipe(map(res => res),
catchError((err) => throwError(err))
);
})
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.