簡體   English   中英

Angular 4-檢查是否所有頁面資源都已完全加載(使加載程序旋轉直到所有資源都完全加載)

[英]Angular 4 - check if all page resources are fully loaded (make loader spins until all resources are fully loaded)

我正在為我的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>

環境:Angular 4.4非常感謝您的幫助,謝謝

只是讓你的組件實現AfterViewInit和集isLoadingfalsengAfterViewInit()

class YourComponent implements AfterViewInit {
    // ...
    ngAfterViewInit() {
        this.isLoading = false;
    }
}

無需附加額外的事件處理程序,即完全覆蓋其生命周期回調的角度覆蓋。

您的問題是您沒有綁定正確的事件。

如果您想知道圖片是否已加載,則需要創建它們並等待它們加載。

首先獲取圖片,然后創建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;
});

之后,您可以隨意使用所選方法顯示它們。

您應該使用ngAfterViewInit生命周期掛鈎並將其中的isLoading設置為false。

TS

export class MyClass implements AfterViewInit {
  isLoading: boolean;

  constructor() {
    this.isLoading = true;
  }

  ngAfterViewInit() {
    this.isLoading = false;
  }
}

的HTML

<app-spinner *ngIf="isLoading"></app-spinner>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM