[英]Add loading html if data not loaded in Angular
我们的应用程序中有许多组件。
一些组件需要服务器提供的数据,然后仅显示html。
在没有数据之前,我们需要显示一些加载栏html。
我试图找出是否对此有任何通用的解决方案?
我可以开始将* ngIf放入每个组件中,但我正在考虑更通用的解决方案。
所以目前我在想。
到现在为止,下面的代码已写入。
@Directive({
selector: '[appCustomLoad]'
})
export class CustomLoadDirective implements AfterViewInit{
constructor(private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef,
private renderer: Renderer,
private el: ElementRef) {
}
@Input() set appCustomLoad(shouldAdd: boolean){
// currently i am passing boolean for testing,
// if i use this solution then i will change boolean to any.
// and if object is not null or undefined then we will show loading bar with some msg.
if(shouldAdd){
this.viewContainer.createEmbeddedView(this.templateRef);
}else{
this.viewContainer.clear();
}
}
ngAfterViewInit(): void {
// after view init
}
}
我无法使用指令在div内添加html。
我不确定这是正确的方法 ,因此,如果您有更好的解决方案,请给我一些想法 。
有一种非常简单的通用方法可以做到这一点,但它并不那么优雅。 解决方案是创建一个全球通用的service.loading变量:
serviceTest.loading = 0;
然后在数据检索中将数量增加1:
serviceTest.loading++;
现在,您可以创建所需的任何加载动画
ng-if="serviceTest.loading > 0"
//display loading gif
检索数据后,将值减小一
serviceTest.loading--;
使用整数而不是布尔值的原因是因为您要支持多个检索。 像那个整数应该上升到3,并且您不希望在所有3个请求完成之前结束加载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.