为时已晚,但也许其他人需要它:
有这方面的包,例如ng2-slim-loading-bar。
但是,如果您想使用 Material Progress Bar 手动执行此操作,请查看此示例。
它确实给人一种进步的错觉,因为它会随着时间的推移而增加,并且如果它达到 95% 而负载还没有完成,那么它就会停止直到发生这种情况。不知道有没有办法计算一个请求的真实进度,那就完美了。
编辑:查看有关 Tracking and showing request progress 的 Angular 文档,这样您也许可以实现一个相当真实的进度条。
组件:
import { Component } from '@angular/core';
import {
NavigationCancel,
Event,
NavigationEnd,
NavigationError,
NavigationStart,
Router,
} from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent {
progressValue = 0;
progressColor = 'primary';
progressTimer: number;
// This will be used to force stop (if an error occurs, or the user stops loading)
stopProgress = false;
constructor(private router: Router) {
this.router.events.subscribe((event: Event) => {
this.navigationObserver(event);
});
}
private navigationObserver(event: Event): void {
if (event instanceof NavigationStart) {
// Increase 1% every 25 milliseconds, adjust it to your preference
this.progressTimer = setInterval(() => {
this.loading();
}, 25);
}
if (event instanceof NavigationEnd) {
// When the navigation finishes, fill the bar completely
this.progressValue = 100;
/*
* Uncomment this block to simulate a delay (for testing), because if you
* are in a local environment or the request is to a 'light' or very fast resource,
* the progress bar will appear at 100%.
*/
/*
setTimeout(() => {
this.progressValue = 100;
}, 2000);
*/
}
/*
* If the navigation is canceled or an error occurs,
* stop the progress bar and change its color.
*/
if (event instanceof NavigationCancel) {
this.stopProgress = true;
this.progressColor = 'accent';
}
if (event instanceof NavigationError) {
this.stopProgress = true;
this.progressColor = 'warn';
}
}
// Function to increase the value of the progress bar
private loading(): void {
/*
* Leave 5% in case an unusual delay occurs, in the previous
* function it is filled to 100% if the load ends successfully
*/
if (this.progressValue >= 95 || this.stopProgress) {
clearInterval(this.progressTimer);
} else {
this.progressValue++;
}
}
}
模板:
<mat-progress-bar [value]="progressValue" [color]="progressColor">
</mat-progress-bar>
<div *ngIf="progressValue == 100; else elseBlock">
<h1>Loaded!</h1>
</div>
<ng-template #elseBlock>
<h1>Loading...</h1>
</ng-template>