Important Note
The issue lies in the backend, not Angular. The requests are correct.
In my Angular5 app, I am trying to upload multiple files at once using rxjs forkJoin
. I store the requests in an array as shown in the code below.
However, after adding the requests to the array, they all turn out to be the same request instead of uploading different selected files. Prior to adding them to the array, individual requests are correctly created by the service. I suspect this might be a pointer issue, and even tried creating a deep copy with Object.assign({}, request)
, but it did not work for the Observable
.
Console log output (ignore the error, the server always rejects the second request due to a unique constraint requirement - this behavior is expected):
https://i.sstatic.net/mVHuI.png
Here's the component code:
uploadFiles() {
var requests = [];
var ctrNoFailuer = this.filesReplace.length;
for (var i = 0; i < this.filesReplace.length; i++) {
let request = this.solutionFileService.update(this.filesReplace[i][0], this.filesReplace[i][1]);
console.log(request);
requests.push(request);
}
if (requests.length == 0) {
this.runTests();
} else {
forkJoin(requests).subscribe(
res => {
// [...]
}
)
}
}
And here's how the service looks like:
update(solutionFile: SolutionFile, file?: File): Observable<SolutionFile> {
console.log(solutionFile);
let url = `${this.url}/src_uploads/${solutionFile.id}/`;
if (file) {
let headers = new HttpHeaders({
'enctype': 'multipart/form-data',
'Authorization': `JWT ${this.authService.getToken()}`
})
const formData: FormData = new FormData();
formData.append('student_solution', String(solutionFile.student_solution));
formData.append('file_src', file, file.name);
return this.httpClient.put<SolutionFile>(url, formData, { headers: headers })
.pipe(
catchError(this.handleError('UPDATE solution-file', new SolutionFile()))
);
}
return this.httpClient.put<SolutionFile>(url, solutionFile, { headers: this.headers })
.pipe(
catchError(this.handleError('UPDATE solution-file', new SolutionFile())
)
);
}