检索数据时显示加载动画 (Angular 10)

Show loading animation while retrieving data (Angular 10)

我在检索数据时试图在 Angular 10 中显示加载动画。如果我使用特定的时间值,我可以显示加载动画,但我无法在收集数据时显示它。请在下面查看我的代码片段。而不是手动调用加载动画,我希望它只 运行 而 'getAllDocuments' 函数是 运行ning。有时我的硬编码时间值太短而其他时间值太长。我希望它每次都是正确的。


ngOnInit() {
    this.getAllDocuments();
    this.triggerLoadingAnimation(12);
  }

  ngAfterViewInit(): void {
    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;
  }

  public triggerLoadingAnimation(num){
    this.spinner.show();

    setTimeout(() => {
      this.spinner.hide();
    }, num*1500);
  }

  async getAllDocuments() {
    this.repoService.getData('/api/Prometheus/Documents')
    .subscribe(res => {
      this.dataSource.data = res as Document[];
    })
  }

您可以使用以下代码:

getAllDocuments() {
 this.spinner.show(); // SHOW WHEN DATA IS LOADING
    this.repoService.getData('/api/Prometheus/Documents')
    .subscribe(res => {
      this.dataSource.data = res as Document[];
     this.spinner.hide();  //  HIDE WHEN DATA IS LOADED
    })
  }

您可以在同一个函数中显示和隐藏微调器,而不用为此创建新函数。

async getAllDocuments() {
    this.spinner.show();
    this.repoService.getData('/api/Prometheus/Documents')
    .subscribe(res => {
          this.dataSource.data = res as Document[];
          this.spinner.hide();
    });
    
}

你很接近。
我还添加了错误处理,删除了不必要的异步,并且 运行 在构造函数中调用 ajax 而不是 ngOnInit 以避免不必要的等待时间。

constructor(private repoService: RepoService) {
    this.getAllDocuments();
}

ngOnInit() {
  // stuff that really need @Input data to be filled
}

ngAfterViewInit(): void {
    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;
}

getAllDocuments() {
    this.spinner.show();
    this.repoService.getData('/api/Prometheus/Documents')
    .subscribe((res: Document[]) => {
      this.dataSource.data = res;
      this.spinner.hide();
    },
    error => {
      this.spinner.hide();
      console.error('error while retrieving documents', error);
      // handle error
    })
}

你做错了,你应该调用微调器来显示 API 调用,并在检索数据时隐藏它。

更好的方法是在构造函数中调用它,因为在完成创建组件时调用 ngOnInit DOM,通过构造函数注入所有必需的依赖项并处理输入绑定

constructor() {
    this.getAllDocuments();
}


ngOnInit() {
    //this.getAllDocuments();
  }

  ngAfterViewInit(): void {
    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;
  }

  async getAllDocuments() {
    this.spinner.show();
    this.repoService.getData('/api/Prometheus/Documents')
    .subscribe((res: Document[]) => {
      this.dataSource.data = res;
    }, (err) => {
        //handle the errors
         console.log(err);
    }, () => {
        this.spinner.hide();
    });
  }

加载微调器是一种很好的用户体验技术,但是您需要加载多少个微调器才能满足用户的需求?可能取决于应用程序的大小。 由于您需要在检索数据时显示一个微调器,因此拥有一个全局微调器将是一个更好的方法。使用全局微调器,无论何时检索数据,都会显示微调器。 下面是一个很好的拦截器实现来显示微调器 Using Interceptor to show spinner