我有在 Angular 13 / RxJs 7 中獲得下載進度的作業解決方案。
首先我定義了一些列舉:
export enum RequestType {
get = 'GET',
post = 'POST',
put = 'PUT',
delete = 'DELETE',
}
export enum ActionType {
download = 1,
upload
}
接下來,我實作了一個共享服務來處理跟蹤進度:
@Injectable({
providedIn: 'root'
})
export class DownloadProgressService {
percentDone = 0;
actionType: ActionType;
constructor(private http: HttpClient) { }
downloadFile(uri: string, requestType: RequestType, actionType: ActionType, body: any): Observable<number> {
this.actionType = actionType;
const req = new HttpRequest(requestType, uri, body, {
reportProgress: true,
responseType: 'blob'
});
return this.http
.request(req)
.pipe(
map(event => this.getPercentage(event)),
);
}
public getPercentage(event: HttpEvent<any>): number {
switch (event.type) {
case HttpEventType.UploadProgress:
// Downloading files will still trigger upload progress due to the back-and-forth, ignore this
if (this.actionType !== ActionType.upload) {
return 0;
}
// Compute and show the % done:
if (event && event.total) {
this.percentDone = Math.round(100 * event.loaded / event.total);
return this.percentDone;
} else {
return 0;
}
case HttpEventType.DownloadProgress:
if (event && event.total) {
this.percentDone = Math.round(100 * event.loaded / event.total);
}
return this.percentDone;
default:
// Not an event we care about
return this.percentDone;
}
}
}
然后,我只需訂閱它并獲得正確的下載進度:
this.downloadService
.downloadFile(url, RequestType.post, ActionType.download, body)
.subscribe(progress => this.progress = progress);
這一切都很好,我的組件庫中有一個進度條,顯示了真實的進度。
問題是......我如何獲得結果檔案?
uj5u.com熱心網友回復:
您可以回傳一個包含進度百分比和HTTP 回應的物件,而不是只回傳進度。
return this.http.request(req).pipe(
map(event => ({
progress: this.getPercentage(event),
response: event
})),
);
現在在訂閱中您可以使用該物件
this.downloadService
.downloadFile(url, RequestType.post, ActionType.download, body)
.subscribe({
next: ({progress, response}) => {
this.progress = progress;
// use response
},
error: (error: any) => {
// handle errors
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/414467.html
標籤:
