[英]Karma | Ionic | Uncaught Error: Uncaught Error: Uncaught (in promise): TypeError: Cannot read property 'getToken' of undefined
[英]Ionic 4: when trying to upload selfie image, Error: Uncaught (in promise): TypeError: Cannot read property 'subscribe' of undefined
我正在使用離子版本 4。嘗試從手機攝像頭拍照並上傳。 最近兩天我試圖解決這個問題。 提前致謝。
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))
);
}
}
您收到該錯誤是因為您正在調用一個 void 方法,但您期望它會返回一個可觀察的。
我建議您創建方法以使閱讀器成為可觀察的並在您的 postFile 上使用平面圖,以便在完成閱讀器可觀察后調用 http 方法。 所以你將使用 postFile 方法,它現在會返回一個 observable。
我創建了一個類似的方法,只是為了向您展示如何正確執行此操作的邏輯。 請根據您的需要進行更改。
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.