'Angular 10 Observable responds multiple times
I have a function in my Angular 10 app where I create a blob and upload a file. When I subscribe to that observable, it responds five times. I cannot figure out where or why?
uploadBacklogUploadFile(data, fileName: string) {
const blob = new Blob([data], { type: 'text/csv' });
this.backlogUploadService
.uploadBacklogFile(blob, fileName, this.selectedJoin.id)
.subscribe(
() => { <-----this block of code will run 5 times
this.uploadPercent = 100;
this.dialogRef.close(true);
this.openDialog();
this.backlogUploaded.emit(true);
},
() => {
this.uploadPercent = 0;
this.snackBar.open('The backlog failed to be uploaded', null, {
panelClass: 'snack-bar-error'
});
},
);
}
And my service
public uploadBacklogFile(file: string | Blob, fileName: string, Id: number): Observable<HttpEvent<any>> {
const requestView = new BacklogUploadRequestView(Id);
const formData: FormData = new FormData();
formData.append('backlogUpload', new Blob([JSON.stringify(requestView)], { type: 'application/json' }), '');
formData.append('file', file, fileName);
const headers = new HttpHeaders({
Accept: 'application/json',
});
const url = this.remoteClientUtils.getThorUrl() + `${this.BACKLOG_UPLOAD_URL}`;
console.log("checkpoint") <------- this will only log once, so it must be nothing above?
return this.httpClient.request(HttpMethods.POST, url, {
body: formData,
headers: headers,
reportProgress: true,
observe: 'events'
})
.pipe(
catchError(this.remoteClientUtils.handleError<HttpEvent<any>>(null)));
}
Solution 1:[1]
You try to track the progress of uploading, when you use reportProgress and observe (https://angular.io/guide/http#requesting-data-from-a-server), I think, you should delete these options
this.httpClient.request(HttpMethods.POST, url, {
body: formData,
headers: headers,
reportProgress: true, //delete this
observe: 'events' // and delete this
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Slawa Eremin |
