如何仅在超过 n 的请求上显示加载栏
How to only show a loading bar on requests taking longer than n
我有一个在每个 HTTP 请求上显示的加载栏。这非常适用于花费超过 300 毫秒左右的请求(例如 API 调用获取大量数据),但当请求很短时看起来很傻,条形闪烁然后消失并且相当分散注意力。
我正在尝试找出如何隐藏加载栏,除非 return 花费的时间长于 n 毫秒。
为了控制加载条,我在 AppCompoent
上有一个简单的方法
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
loading: boolean = true;
constructor(private router: Router) {
router.events.subscribe((routerEvent: Event) => {
this.checkRouterEvent(routerEvent);
});
}
checkRouterEvent(routerEvent: Event): void {
if (routerEvent instanceof NavigationStart) {
// sleep here for n ms perhaps?
this.loading = true;
}
if (routerEvent instanceof NavigationEnd ||
routerEvent instanceof NavigationCancel ||
routerEvent instanceof NavigationError) {
this.loading = false;
}
}
}
或者我已经完全错过了如何处理这种情况的标准模式?
您可以只添加一个新变量来说明 "finished loading" 状态。
这是一个解决方案:在您的 class 中添加一个 finishedLoading: boolean = true;
。那么:
checkRouterEvent(routerEvent: Event): void {
if (routerEvent instanceof NavigationStart) {
this.finishedLoading = false;
this.loading = false;
setTimeout(() => {
if (!this.finishedLoading) {
this.loading = true;
}
} , 300);
}
if (routerEvent instanceof NavigationEnd ||
routerEvent instanceof NavigationCancel ||
routerEvent instanceof NavigationError) {
this.finishedLoading = true;
this.loading = false;
}
}
我有一个在每个 HTTP 请求上显示的加载栏。这非常适用于花费超过 300 毫秒左右的请求(例如 API 调用获取大量数据),但当请求很短时看起来很傻,条形闪烁然后消失并且相当分散注意力。
我正在尝试找出如何隐藏加载栏,除非 return 花费的时间长于 n 毫秒。
为了控制加载条,我在 AppCompoent
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
loading: boolean = true;
constructor(private router: Router) {
router.events.subscribe((routerEvent: Event) => {
this.checkRouterEvent(routerEvent);
});
}
checkRouterEvent(routerEvent: Event): void {
if (routerEvent instanceof NavigationStart) {
// sleep here for n ms perhaps?
this.loading = true;
}
if (routerEvent instanceof NavigationEnd ||
routerEvent instanceof NavigationCancel ||
routerEvent instanceof NavigationError) {
this.loading = false;
}
}
}
或者我已经完全错过了如何处理这种情况的标准模式?
您可以只添加一个新变量来说明 "finished loading" 状态。
这是一个解决方案:在您的 class 中添加一个 finishedLoading: boolean = true;
。那么:
checkRouterEvent(routerEvent: Event): void {
if (routerEvent instanceof NavigationStart) {
this.finishedLoading = false;
this.loading = false;
setTimeout(() => {
if (!this.finishedLoading) {
this.loading = true;
}
} , 300);
}
if (routerEvent instanceof NavigationEnd ||
routerEvent instanceof NavigationCancel ||
routerEvent instanceof NavigationError) {
this.finishedLoading = true;
this.loading = false;
}
}