Select a randomly generated number from an array, which dynamically updates every time the browser is refreshed

I recently completed a project in Angular that utilizes the TMDB API. The project is nearly finalized, but I have a desire to implement a change where the background image (backdrop_path) and other elements shift each time the browser is reloaded. Currently, this data is being manually fetched from the TMDB API. Thank you.

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;
    }));
  }

Answer №1

Solution:

...
randomNumber: number;
comedy!: Movies;
....
// Insert this code within your subscribe block
this.comedy = data;
const min = 0;
// Adjust for zero-based indexing in arrays
const max = this.comedy.results.length - 1;
// Generate a random number within the range
this.randomNumber = Math.floor(Math.random() * (max - min + 1) + min);
// Utilize randomNumber variable instead of hardcoding 5
this.headerBGUrl = 'https://image.tmdb.org/t/p/original' + this.comedy.results[this.randomNumber].backdrop_path;

Replace all instances of 5 with randomNumber throughout your HTML.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using TypeScript to chain observables in a service and then subscribing to them in the component at the end

Working with Platform - Angualar 2 + TypeScript + angularFire2 Within my user.service.ts file, I have implemented the following code to initiate an initial request to a firebase endpoint in order to fetch some path information. Subsequently, I aim to util ...

Enhance Data Grid functionality in Angular 8 using DevExpress library

I'm struggling to grasp how the DxDataGridComponent extension works. My first step is extending the DxDataGridComponent like this: import { Component } from '@angular/core'; import { DxDataGridComponent } from 'devextreme-angular/ui/d ...

What is the best way to monitor updates made to a function that utilizes firestore's onSnapShot method?

I am currently working with the following function: public GetExercisePosts(user: User): ExercisePost[] { const exercisePosts = new Array<ExercisePost>(); firebase.firestore().collection('exercise-posts').where('created-by&apo ...

Having trouble getting `npm start` to work for the Lite-server?

As a newcomer to Angular and web programming, I attempted to replicate the quickstart project on github/angular by using "npm start" to initiate lite-server. However, following a tutorial [link] (https://www.youtube.com/watch?v=-zW1zHqsdyc&t=804s), I ...

Having difficulties in accessing an API with Ionic 3

Whenever I attempt to connect with an API, I keep encountering the Cross-Origin Read Blocking (CORB) blocked cross-origin response error. Can anyone provide guidance on how to resolve this issue? Any assistance would be greatly appreciated. ...

The possibility exists that the onClick function may be null

I am encountering an issue with a props function that is showing an error message stating that the object may be null. import {Dropdown} from "react-bootstrap"; interface GenreButtonProps { key: number; id: number | null; genre: strin ...

Typescript is struggling to locate a module that was specified in the "paths" configuration

Within my React project, I have set up a module alias in the webpack config. Now, I am looking to transition to Typescript. // I have tried to simplify the setup as much as possible Here is my tsconfig.json located in the root directory: { "compilerOp ...

Sorting the material table based on the column IDs, which usually correspond to the column names, may not align with the properties of the data

.ts this.displayedColumns = [ { key: 'id', header: '#' }, { key: 'fullname', header: 'Full name' }, { key: 'email', header: 'email' }, { key: 'roleName', header: ...

Using the Angular JSON pipe with angular-datatables

I am currently utilizing angular-datatables to exhibit NoSQL de-normalized data in a grid format for visualization purposes. Within my dataset, I have several intricate nested JSON objects and I intend to showcase a specific cell with formatted JSON using ...

How to retrieve a random element from an array within a for loop using Angular 2

I'm in the process of developing a soundboard that will play a random sound each time a button is clicked. To achieve this, I have created an array within a for loop to extract the links to mp3 files (filename), and when a user clicks the button, the ...

Is there an array containing unique DateTime strings?

I am dealing with an Array<object> containing n objects of a specific type. { name: 'random', startDate: '2017-11-10 09:00', endDate: '2017-11-23 11:00' } My goal is to filter this array before rendering the resu ...

Accessing Next and Previous Elements Dynamically in TypeScript from a Dictionary or Array

I am new to Angular and currently working on an Angular 5 application. I have a task that involves retrieving the next or previous item from a dictionary (model) for navigation purposes. After researching several articles, I have devised the following solu ...

Calculating the number of objects returned from Firebase in an Angular 2

I am currently developing a booking component in Angular 2. Once a booking is created, the information gets sent to the firebase database under the bookings node. In order to display on the home screen dashboard of the application whether the admin has a ...

What is the best way to specify a function type that takes an argument of type T and returns void?

I am in search of a way to create a type that can accept any (x: T) => void function: let a: MyType; a = (x: number) => {}; // (x: number) => void a = (x: string) => {}; // (x: string) => void a = (x: SomeInterface) => {}; / ...

Creating a release of an Angular 12 library using Ivy and sharing it on npm

Recently, I had the task of updating a library to angular 12. After successfully compiling it with Ivy full compilation mode, I realized that it cannot be published on npm in this state. Following suggestions from various sources, I tried setting "enableI ...

How to eliminate the button from Google Maps API using JavaScript

I am trying to implement a specific functionality on my map. When the user drags the map, I want a button named 'Search in this area' to appear. Once the user clicks on the button, it should disappear so that the search can't be performed ag ...

Angular i18n simplifies the process of internationalizing and local

Is there a way to display different labels based on the user without using conditionals? I want to maintain consistency in this large project. For example: When User 1 is logged in: <h1>Hello, I am User 1</h1> When User 2 is logged in: < ...

Using the keyof lookup in a Typescript interface is a powerful way to

I'm looking for a solution similar to: interface Operation<T, K extends keyof T> { key: keyof T; operation: 'add' | 'remove'; value: T[K]; } but without the necessity of passing K as a template. Essentially, I want to ...

Ways to address the Generic Object Injection Sink eslint error (security/detect-object-injection)

I am seeking a solution to resolve this issue without needing to deactivate eslint. Moreover, I am eager to comprehend the cause of the error. const getMappedCard = (cardName: CardName) => { const mappedCards = { Mastercard: <Mastercard /> ...

Angular 7 ESRI loader search widget focus out bug: finding a solution

I am currently working on implementing an ESRI map using esri-loader in my Angular application. Everything seems to be working fine, but I am encountering an error when typing something into the search widget and then focusing out of it. "Uncaught Typ ...