Angular 4-检查是否所有页面资源都已完全加载(使加载程序旋转直到所有资源都完全加载)

hzb*_*kan 6 javascript typescript angular

我正在为我的Angular应用程序创建一个加载程序。

最常见的方法是在订阅http请求时传递boolean参数,但是我的服务的响应是一系列图像URL,因为页面上充满了图像。

因此,当重新获取URL时,加载程序停止了,但是由于连接速度慢,由于图像尚未完成加载而使用户烦恼。

我尝试使用Javascript的load事件来监听我的资源完成加载后的时间,因此我可以在那时停止加载程序,但是似乎我无法通过侦听器函数来操纵加载程序的值。

这是我尝试过的:

//the TS component 
isLoading: boolean;

ngOnInit() {
this.isLoading = true;
this.checkIfLoaded();
}

checkIfLoaded() {
  window.addEventListener("load", function (event) {
    console.log("All resources finished loading!");
    //here i should do something, either returning false or...
    //...manipulating the isLoading, but i can't access isLoading from here
  });
}


//the template
<ng-container *ngIf="isLoading">
   <app-spinner></app-spinner>
</ng-container>
Run Code Online (Sandbox Code Playgroud)

环境:Angular 4.4非常感谢您的帮助,谢谢

chr*_*con 6

只需使您的组件实现AfterViewInit并设置isLoadingfalsein即可ngAfterViewInit()

class YourComponent implements AfterViewInit {
    // ...
    ngAfterViewInit() {
        this.isLoading = false;
    }
}
Run Code Online (Sandbox Code Playgroud)

无需附加额外的事件处理程序,即完全覆盖其生命周期回调的角度覆盖。

  • ngAfterViewInit 仍然触发得太快 (12认同)
  • ngAfterViewInit 在渲染组件视图之后但在加载所有库并且页面实际完全加载之前触发。 (2认同)

小智 5

您的问题是您没有绑定到正确的事件。

如果您想知道图片是否已加载,则需要创建它们并等待它们加载。

首先获取您的图片,然后创建 HTML 元素来加载它们,然后等待所有这些都已加载,最后显示它们:

haveImagesLoaded: boolean[];

this.myService.getPictures().subscribe((urls: string[]) => {
  // no image has loaded, put them all to false
  this.haveImagesLoaded = urls.map(url => false);

  // Iterate over the images
  urls.forEach((url, index) => {
    // Create an HTML image
    let img = new Image();
    // Listen to its loading event
    img.onload = () => {
      // Image has loaded, save the information
      this.haveImagesLoaded[index] = true;
      // If all images have loaded, set your loader to false
      this.isLoading = !this.haveImagesLoaded.some(hasLoaded => !hasLoaded);
    };
  });
  // trigger the loading of the image
  img.src = url;
});
Run Code Online (Sandbox Code Playgroud)

之后,您可以使用您选择的方法自由地显示它们。