angular - 在数组中取一个随机数,每次浏览器重新加载它都会改变
问题描述
我在使用 TMDB API 的 Angular 中做了这个项目,该项目几乎完成了,但我想进行更改,每次重新加载浏览器时,背景图像(backdrop_path)和其他项目都会更改。目前,此信息是来自 TMDB API 的手动信息。感激的
Service *****
getComedy(): Observable<Movies> {
return this.http.get<Movies>(`${this.url}${endpoint.comedy}`, { params } )
}
Component HEADER ****
<div class="header__banner" [ngStyle]="{'background' : 'url(' + headerBGUrl + ')'}">
<div class="featured--horizontal">
<div class="featured--vertical"></div>
</div>
<div class="info">
<div class="title">
<h2>{{ comedy.results[5].title }}</h2>
<span class="points">Nota: </span>
<span class="points">{{ comedy.results[5].popularity | number:'1.1-1'}}</span>
<span>{{ comedy.results[5].release_date | date:'yyyy' }}</span>
</div>
<p>{{ comedy.results[5].overview }}</p>
<div class="info-btns">
<button class="watchButton">► Assistir</button>
<button class="listButton">+ Minha Lista</button>
</div>
</div>
</div>
****
Component Header Typescript *****
subs: Subscription[] = []
sticky!: boolean;
comedy!: Movies;
@ViewChild('stickHeader') header!: ElementRef;
headerBGUrl!: any;
constructor(public movies: ServiceApiService) { }
ngOnInit(): void {
this.subs.push(this.movies.getComedy().subscribe(data => {
this.comedy = data;
this.headerBGUrl = 'https://image.tmdb.org/t/p/original' + this.comedy.results[5].backdrop_path;
}));
}
解决方案
尝试:
...
randomNumber: number;
comedy!: Movies;
....
// this code is inside of your subscribe
this.comedy = data;
const min = 0;
// subtract one because arrays are zero index
const max = this.comedy.results.length - 1;
// create a random number between two values
this.randomNumber = Math.floor(Math.random() * (max - min + 1) + min);
// use randomNumber variable instead of 5
this.headerBGUrl = 'https://image.tmdb.org/t/p/original' + this.comedy.results[this.randomNumber].backdrop_path;
在您的 HTML 中的任何地方,都5
将其更改为randomNumber
.
推荐阅读
- typescript - 属性“提交”不存在
- python - python为什么我不能在将它附加到for循环后清除列表而不保持清除
- angular - 从 DB 通过 HTML 传递 Angular 自定义组件
- typescript - 解构时类型推断丢失
- reactjs - Redux如何设置初始状态
- c++ - std::packaged_task 是如何复制我的转发参考参数的?
- flutter - 具有省略号功能的 Flutter Wrap 小部件
- swift - 无法调用非函数类型“ViewRouter”的值
- .net - 如何在 WPF 应用程序中从智能手机导入多个文件?
- laravel - Laravel 和 React 通过 Storage Facades 上传图片失败