我想在来自 rest-api 的图像上显示加载指示器。我的代码当前在数据中加载请求时在图像上显示加载指示器,但是当我转到分页的不同页面时,图像不会在 View 上显示加载指示器,因为加载仅基于何时数据加载了吗?那么如何在 View 中显示加载指示器呢?到目前为止我的代码是:
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 将隐藏微调器。
关于javascript - 如何从 rest-api 在 Angular 中的图像上显示加载指示器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59121442/