首页 > 解决方案 > 在数组中取一个随机数,每次浏览器重新加载它都会改变

问题描述

我在使用 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;
    }));
  }

标签: angulartypescriptapi

解决方案


尝试:

...
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.


推荐阅读