1

I am building an video saving service as a project and have an array of the user's saved videos obtained from the database response.array[], I then push the videoId into an display array video[] but on displaying the respective videoId using console.log() it keeps coming undefined.

I have the code snippet as below.

let video = [];
this.service.nextVideo().subscribe( response =>
{
    response.array.forEach(element => {
    video.push(element.videoId);
  });
})
console.log(video[0]); //Output is undefined

The full code snippet is like such

nxtVideo(){
    let video = [];
    this.service.nextVideo().subscribe( response => 
    {
        response.array.forEach(element => {
          console.log(element.videoId);//Display's video id
          video.push(element.videoId);
        });
    })
    console.log(video[0]); //Output undefined
    console.log(video); //Output shows all elements but on accessing specific elements it shows undefined
    return (video[this.offset++]); //offset is a global variable to measure watched videos
  }

  Launch(){
    let videoId = this.nxtVideo();
    //The Display table starts here
  }
Nithin
  • 1,387
  • 4
  • 19
  • 48

1 Answers1

0

Try this code. it must be work, since its asynchronous function.

let video = [];
this.service.nextVideo().subscribe( response =>
{
    response.array.forEach(element => {
       video.push(element.videoId);
    });
    console.log(video[0]); //Output is undefined
})
Le Dinh Dam
  • 112
  • 7
  • Thanks for the answer, but i need to return `video[0]` to another variable as this entire snippet comes inside a different function. similar to this `nextVideo = Video();` and `Video()` is the code snippet. It may not always be `video[0]` and may be any value let say `video[k]` – Nithin Oct 20 '17 at 10:55
  • can u give full file? – Le Dinh Dam Oct 20 '17 at 10:58
  • I have updated the question. Thanks. – Nithin Oct 20 '17 at 11:08