Display a random word, from a JSON object stored in MongoDB, every 5 seconds

0

I have an Ajax request that extracts data from a JSON object created in MongoDB and shows them to me on the screen. But what I'm stuck in is showing a word, from that array, randomly every 5 seconds. I have made the setInterval and it works, but I have tried to do a math.random to the words and nothing, I do not get it. I leave the code of my component.ts

export class FiveWordsComponent implements OnInit {
  public words: Word[];
  constructor(
    private _wordService: WordService

  ) { }

  ngOnInit() {
    setInterval(() => {
      this.getWords();
    }, 5000);
  }

  getWords(){
    this._wordService.getWords().subscribe(
      response => {
        if(response.word){

          this.words=response.word[0].words;

        }
      },
      error => {
        console.log(<any>error);
      }
    );
  }

}

And now I leave you my .html

<!DOCTYPE html>
<html lang="es" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Cinco palabras</title>
  </head>
  <body>
    <app-header></app-header>
    <section id="content">

      <ul>
        <li *ngFor="let word of words" class="list-words">{{word}}</li>
      </ul>


      <!-- audio -->
      <!-- <app-audio></app-audio>   -->
    </section>
    <app-footer></app-footer>
  </body>
</html>

I attach the JSON, the data is for proof.

{
    "_id" : ObjectId("5beeb5fb822c52a42c7c93da"),
    "words" : [ 
        "hola", 
        "adsfsd", 
        "gf", 
        "wrr", 
        "kj", 
        "klj", 
        "lkj", 
        "kj", 
        "klj", 
        "kj", 
        "klj", 
        "kj", 
        "klj", 
        "kj", 
        "klj"
    ],
    "images" : [],
    "thematics" : [],
    "terminations" : [],
    "histories" : []
}

Thank you very much.

Greetings

    
asked by Jaime García 20.11.2018 в 13:12
source

1 answer

1

To generate a random number that within the length of the array of words you must execute the following code Math.floor(Math.random() * (words.length - 1)) + 0 subtracting the length one so that it is the maximum index of the array.

  • Math.floor returns the maximum integer less than or equal to a number.
  • Math.random returns a decimal number between 0 (Included) and 1 but not including it (excluded), which can be scaled to the desired range.
  • Multiply by the desired maximum number, in this case the length of the array - 1 (since the indexes start at 0 to length-1).
  • Finally the result of the integer obtained in Math.floor is added to the desired minimum, in this case 0 since we want a random number that includes the entire array.

An example in JS, you should put the function inside the component and type both the variables and the return of the fn

const words = [ 
        "hola", 
        "adsfsd", 
        "gf", 
        "wrr", 
        "kj", 
        "klj", 
        "lkj", 
        "kj", 
        "klj", 
        "kj", 
        "klj", 
        "kj", 
        "klj", 
        "kj", 
        "klj"
    ];


function getRandomWord() {
  // 0 es el mínimo del rango que puede retornar, lo dejo por si luego alguien precisa de otro número que se pueda basar
  // words.length obtiene la longitud, le restamos 1 ya que superariamos el indice del array
  // Math.floor Devuelve el máximo entero menor o igual a un número. (https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Math/floor)
  const randomNum = Math.floor(Math.random() * (words.length - 1)) + 0;
  return words[randomNum];
}

console.log(getRandomWord());

Your component should look like this:

    export class FiveWordsComponent implements OnInit {
      public words: string[];
      public word: string;
      constructor(
      private _wordService: WordService

       ) { }

      ngOnInit() {
         this.getWords();
         setInterval(() => {
           this.word = this.getRandomWord();
         }, 5000);
       }

     getRandomWord(): string {
       const randomNum: number = Math.floor(Math.random() * (this.words.length - 1)) + 0;
       return this.words[randomNum];
     }

     getWords(){
       this._wordService.getWords().subscribe(
         response => {
           if(response.word){

             this.words=response.words;

           }
         },
         error => {
           console.log(<any>error);
         }
       );
     }

   }

View:

<!DOCTYPE html>
<html lang="es" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Cinco palabras</title>
  </head>
  <body>
    <app-header></app-header>
    <section id="content">

      <ul>
        <li>{{word}}</li>
      </ul>


      <!-- audio -->
      <!-- <app-audio></app-audio>   -->
    </section>
    <app-footer></app-footer>
  </body>
</html>
    
answered by 20.11.2018 / 13:43
source