Answer the question
In order to leave comments, you need to log in
What is the strange behavior of Observable in conjunction with xhr.upload.onprogress?
Listen to my story.
I'm fiddling with Angular 2.
I made a service that sends files to the server with Ajax, at the same time counts percentages on the xhr.upload.onprogress event and writes it to its (service) sv-in.
I made another service that receives files from the form input, uploads them through the first service, and at the same time displays the download progress status. As you can see, it is mainly responsible for interacting with the view.
Well, of course, I wanted to try out Observable, so that the value of the onprogress property inside the 1st service (which, I remind you, is updated asynchronously in the onprogress event), monitor inside the 2nd service and immediately display it beautifully in the form of a bootstrap progressbar.
And here are the miracles. First code:
The 1st service that sends files by Ajax, an Observable object is created in it. I give only the constructor and the method of filling.
constructor () {
this.progress$ = new Observable(observer => {
this.progressObserver = observer
}).share();
}
private makeFileRequest (url: string, params: string[], files: File[]): Promise<any> {
return new Promise((resolve, reject) => {
let formData: FormData = new FormData(),
xhr: XMLHttpRequest = new XMLHttpRequest();
for (let i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
};
xhr.upload.onprogress = (event) => {
this.progress = Math.round(event.loaded / event.total * 100);
this.progressObserver.next(this.progress);
};
xhr.open('POST', url, true);
xhr.send(formData);
});
}
this.fileUploadService.progress$.subscribe(progress => {
this.uploadProgress = progress
});
this.fileUploadService.upload('/api/upload-file', [], this.file);
setInterval(() => {
}, 500);
private makeFileRequest (url: string, params: string[], files: File[]): Promise<any> {
return new Promise((resolve, reject) => {
let formData: FormData = new FormData(),
xhr: XMLHttpRequest = new XMLHttpRequest();
for (let i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
};
setInterval(() => {
}, 500);
xhr.upload.onprogress = (event) => {
this.progress = Math.round(event.loaded / event.total * 100);
this.progressObserver.next(this.progress);
};
xhr.open('POST', url, true);
xhr.send(formData);
});
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question