[英]How to show loading indicator on images in Angular from rest-api
我想在來自 rest-api 的圖像上顯示加載指示器。 我的代碼當前在數據中加載請求時在圖像上顯示加載指示器,但是當我轉到分頁的不同頁面時,圖像不會在視圖上顯示加載指示器,因為加載僅基於何時數據加載了嗎? 那么如何在視圖中顯示加載指示器呢? 到目前為止我的代碼是:
component.html
<div class="col-lg-2 col-md-2 col-sm-12">
<img [hidden]="!imageLoader" src="../../../../assets/images/rolling.gif"/>
<img [hidden]="imageLoader" (load)="this.imageLoader = false;" class="align-self-start mr-5 mb-5 artwork" src="{{itunes.artworkUrl100}}" alt="image">
</div>
component.ts
import { Component, OnInit } from '@angular/core';
import { ApiService } from '../../../services/api.service';
import { faSearch } from '@fortawesome/free-solid-svg-icons';
import { faRedo } from '@fortawesome/free-solid-svg-icons';
import { faHeadphones } from '@fortawesome/free-solid-svg-icons';
import { faExternalLinkAlt } from '@fortawesome/free-solid-svg-icons';
import { faPlus } from '@fortawesome/free-solid-svg-icons';
import { PlaylistService } from '../../../services/playlist.service';
@Component({
selector: 'app-content',
templateUrl: './content.component.html',
styleUrls: ['./content.component.scss']
})
export class ContentComponent {
public data = '';
public apiData: any;
public results = [];
public loading = false;
public noData: any;
clicked = false;
imageLoader = true;
p: number = 1;
faSearch = faSearch;
faRedo = faRedo;
faHeadphones = faHeadphones;
faExternalLinkAlt = faExternalLinkAlt;
faPlus = faPlus;
searchQuery: string = "";
clickMessage = '';
constructor(
private api: ApiService,
private list: PlaylistService
) { }
getAll() {
this.data = '';
this.loading = true;
this.api.getAll(this.searchQuery).subscribe((results) => {
console.log('Data is received - Result - ', results);
this.data = results.results;
this.loading = false;
if (this.data.length == 0) {
this.noData = true;
} else if (this.data.length) {
this.noData = false;
} else {
this.noData = false;
}
})
}
closeAlert() {
this.noData = false;
}
addSongToPlaylist(itunes) {
this.list.playlist.push(Object.assign({}, itunes));
this.list.savePlaylist();
console.log('Playlist - ', this.list.playlist);
}
refresh(): void {
window.location.reload();
}
Search() {
this.api.getAll(this.searchQuery).subscribe((results) => {
this.loading = true;
console.log('Data is received - Result - ', results);
this.data = results.results;
this.loading = false;
})
}
ngOnInit() {
this.list.getPlaylist();
}
}
您可以使用 css 解決此問題,而不是使用一些變量來跟蹤每個圖像以隱藏/顯示微調器。
如果您將 component.html 更改為
<div class="col-lg-2 col-md-2 col-sm-12">
<img (load)="$event.target.classList.add('image-loaded')" class="align-self-start mr-5 mb-5 artwork" src="{{itunes.artworkUrl100}}" alt="image">
<img class="spinner" src="../../../../assets/images/rolling.gif"/>
</div>
並使用這個CSS
.image-loaded + .spinner {
display:none;
}
這個想法是一旦你的圖像加載,類'image-loaded'就會被添加到圖像中。 一旦發生這種情況,css 將隱藏微調器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.