angular - Observable.subscribe 並不總是執行 http 請求
我正在嘗試編寫 Angular 應用程式以將切片文件發送到後端。
我正在對檔案做的事:
- 將多個檔案切割成陣列(每個切片 1MB)
const array = [];
for (let i = 0; i < this.File.file.size; i += 1048576) {
array.push(this.File.file.slice(i, i + 1048576));
}
- 對每個文件調用函數 UploadAllSlices()
private UploadAllSlices() {
let sliceNumber = 0;
const fileUploadSub: Subject<void> = new Subject();
const chunkObserver = new Observable(observer => {
const chunkUploadSub: Subscription = fileUploadSub.subscribe(
_ => {
this.uploadFile(sliceNumber).subscribe((chunkReponse: any) => {
// my logic here
},
e => {
console.log('ERROR', e);
}
);
sliceNumber++;
fileUploadSub.next();
});
}).pipe(
takeUntil(this.pause$),
retry(1000)
);
}
- 函數 uploadFile(在 UploadAllSlices() 內部使用)
private uploadFile (index: number) {
const formData = new FormData();
formData.append(); // other data not important
formData.append(); // other data not important
formData.append('SliceContent', this.File.array[index]);
return this.http.patch(URL , formData).pipe(
retry(1000),
takeUntil(this.pause$)
);
}
當我上傳 1-3 個檔案時,一切運作完美。但當我嘗試一次上傳 10-15 個檔案時,有些檔案會隨機卡住。(有時所有檔案都上傳完成,有時 1-2 個檔案卡住,有時 5 個檔案卡住,非常隨機)
對於那些卡住的檔案,this.http.patch 沒有被執行,所以我無法獲得回應並在這裡進行我的邏輯:
this.uploadFile(sliceNumber).subscribe((chunkReponse: any) => {
// logic here
}
有沒有辦法知道為什麼它會隨機卡住,以及為什麼訂閱不會向後端發送 http.patch?
答案#1
你沒有處理錯誤。
return this.http.patch(URL , formData).pipe(
retry(1000),
takeUntil(this.pause$),
catchError(() => of(null))
);
或
this.uploadFile(sliceNumber).subscribe(
(chunkReponse: any) => { /* logic here */ },
(err) => console.log('oops', err);
);
如果一個 Observable 流在錯誤發生時沒有被處理,它將會停止運作並且不再發出任何值(儘管 HTTP Observable 只會發出一次然後完成——除非它發生錯誤)。請注意,來自 of(null) 的 null 會被傳遞到成功區塊,這就是為什麼你只需要這兩種方法中的其中一種。在你的情況下,第二種方法可能更合適,因為它會提供更多有關 HTTP 錯誤的資訊。
你的瀏覽器除錯控制台的網路分頁也應該能提供更多關於 HTTP 錯誤的資訊。
我在腦中想知道,連續上傳 15 個 1MB 的 HTTP 請求在瀏覽器上有哪些限制。也許是瀏覽器限制導致失敗。同時檢查你的伺服器是否收到了這些請求,如果收到了,它會給出什麼回應。
