Angular Listening用于启动和完成网络调用(下载功能),以显示进度条或微调器



我有一个下载功能,它是通过点击按钮启动的。当这种情况发生时,我想在网络调用发生时显示进度条/微调器,然后在下载开始后隐藏进度条/旋转器。

我将使用有角度的材料垫进度条。我的想法是监听网络调用的开始,并将其定义为isLoading=true,其完成将导致文件链接或错误,并将isLoading=false设置为隐藏进度条,例如

<mat-progress-bar mode="indeterminate *ngIf 
="isLoading"</mat-progress-bar>

以显示和隐藏进度条。

我试着这样做:

this.documents.find(document => document.id 
=== element.id).isLoading = true 

然后在我的订阅中将isLoading定义为false,但这并不是我需要做的。

这是我的下载功能:

download(element: Document | TDoc, index: 
number) {if (
(!this.isTDoc && ! 
(<Document>element).files.length) ||
(this.isTDoc && !(<isTDoc>element).url)
)
return;
if (this.isTDoc) {
const url = (<TDoc>element).url;
const fileName = `${(<TDoc>element).itemName}.pdf`;
downloadLink(url, fileName);
} else {
const query = 'index=' + index.toString();
this.documentService
.downloadDocument((<Document>element).serialnumber, query)
.pipe(
filter(res => !!res),
take(1)
)
.subscribe(res => {
const fileName = `${(<Document>element).serialnumber}.pdf`;
downloadBlob([res], fileName, 'application/pdf');
});
}

我的文档服务是:…

downloadDocument(serialNumber: string, query: 
string) {
const url = someURL(serialNumber, query);
return this.dataService.asyncRequest(
RequestTypes.GET,
url,
null,
ServerHosts.TDocSERVER,
{
responseType: 'arraybuffer'
}
);

我的另一个尝试是创建DocumentDownloadActions文件,定义REQUEST/SSUCCESS/FAILURE,然后在调用函数时为isLoading=true,然后在出现文件或错误时为before-end。

this.someDownloadService.get('someApiUrl', 
somePayload).pipe(
map((res) => {
this.dispatch(new DownloadSuccessAction());
return res;
}),
catch((err) => {
this.dispatch(new DownloadFailureAction());
})

因为我可以使用Value将进度条与网络进度相匹配,所以听HTTP调用会是更好的方法吗?

您可以使用*ngIF="isLoading"显示或隐藏进度条。我实现了一个简单的场景来展示功能。有输入和搜索按钮。无论用户输入什么,点击搜索按钮,API调用都会被实例化,并显示API的返回数据。单击时,我将设置this.isLoading=true,一旦我们得到API响应,我将其设置为false,即this.isLoading=false。代码片段:

public onSearch(): void {
this.isLoading=true;
this.searchItems = [];
const tag: string = this.searchItem;
this.sampleService
.search(tag)
.pipe(
finalize(() => (this.isLoading = false)),
first()
)
.subscribe(
results => {
this.searchItems = results.query.search;
},
(error) => {
console.log('Error: '. error);
}
);
}

在HTML:中

<input placeholder="Search something" [(ngModel)]="searchItem"/><button 
(click)="onSearch()">Search</button>
<mat-progress-bar *ngIf="isLoading" mode="indeterminate"></mat-progress-bar>
<hr>
<h2>Search result:</h2>
<div *ngIf="searchItems && searchItems.length>0">
<div *ngFor="let item of searchItems">
<h4>{{item?.title}}</h4>
</div>
</div>

请在下面的链接中找到代码示例:

https://stackblitz.com/edit/angular-sf-mat-progress-bar?file=src%2Fapp%2Fapp.component.ts

演示网址:

https://angular-sf-mat-progress-bar.stackblitz.io

希望这能解决你的问题。

最新更新