Search code examples
angularangular6angular7themoviedb-api

Angular 7 getting multiple value from the json


Json example but getting json data from service:

{"id":384018,"results":[{"id":"5c54548b0e0a2612ccd3d25f","iso_639_1":"en","iso_3166_1":"US","key":"9SA7FaKxZVI","name":"Fast & Furious Presents: Hobbs & Shaw - Official Trailer [HD]","site":"YouTube","size":1080,"type":"Trailer"}, {"id":"5cbb2b460e0a2641edef37e0","iso_639_1":"en","iso_3166_1":"US","key":"HZ7PAyCDwEg","name":"Fast & Furious Presents: Hobbs & Shaw - Official Trailer #2 [HD]","site":"YouTube","size":1080,"type":"Trailer"}, {"id":"5d16c00905a533001e7c69dd","iso_639_1":"en","iso_3166_1":"US","key":"b736ZM_KfEk","name":"Fast & Furious Presents: Hobbs & Shaw - In Theaters 8/2 (Final Trailer) [HD]","site":"YouTube","size":1080,"type":"Trailer"}]}

service

 getMovieVideos(id: string): Observable<any> {
    const params = new HttpParams()
      .set('api_key', this.apikey);
    return this.http.get('<<my_api_url>>' + id + '/videos', { params })

  }

Component

import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { ActivatedRoute } from '@angular/router';
import { MoviesService } from '../movies.service';

@Component({
  selector: 'app-movie-video',
  templateUrl: './movie-video.component.html',
  styleUrls: ['./movie-video.component.css']
})
export class MovieVideoComponent implements OnInit {
  movie: Object;
  video: Object;
  constructor(
    private _moviesServices: MoviesService,
    private router: ActivatedRoute,
    private sanitizer: DomSanitizer
  ) {

  }
  ngOnInit() {
    this.router.params.subscribe((params) => {
      const id = params['id'];
      this._moviesServices.getMovie(id).subscribe(movie => {
        this.movie = movie;
      });
      this._moviesServices.getMovieVideos(id).subscribe((res: any) => {
        if (res.results && res.results.length) {
          this.video = res.results[0];
          this.video['url'] = this.sanitizer.bypassSecurityTrustResourceUrl('https://www.youtube.com/embed/' + this.video['key']);
        }
      });
    })
  }
}

HTML:

<div class="row mt-3" *ngIf="video">
    <div class="col-12">
        <div class="embed-responsive embed-responsive-16by9">
            <iframe class="embed-responsive-item" [src]="video.url" allowfullscreen></iframe>
        </div>
    </div>
</div>

Currently i am able to show only one video(json is "key"), but want to show all the videos from the json results here.


Solution

  • You need to use ngFor as follows

    <div *ngFor="let video of myObj.results">
      <iframe [src]="('https://www.youtube.com/embed/' + video.videoURL) | safe"></iframe>
    </div>
    

    STACKBLITZ DEMO