Fetch YouTube Videos Using YouTube Data API V3 In Angular 5!

5
1003
views

Fetch YouTube Videos Using YouTube Data API V3 In Angular 5!

YouTube Data API has now moved from version 2 to version 3. Some of the things have been changed! As I went through their documentation I didn’t feel like they have explained concepts in detail!

Here In this blog I am gonna show you How to fetch your channel YouTube videos and display it in your website! If want you can play around with YouTube Data API Explorer, I think that is good practice to form your particular data API URL to make API calls.

As I tried to do this in Angular 5 I struggled with some of the concepts like DomSanitizer(We will see it in a bit later…). I went ahead and raised the questions in stackoverflow but later I found answers myself.

As I mentioned DomSanitizer! You might be wondering what is DomSanitizer and Why It is and all! Angular is very specific about the safety of URL’s which you are going to put them to display the videos or for any other stuff. You need to filter through each URL and make them safe. So we are going to use pipe to filter through URLs making them safe.

You need to create a yourfilename.pipe.ts file and make sure you register it in app.module.ts under declarations.

Fetch YouTube Videos Using YouTube Data API V3 In Angular 5!

Our filename.pipe.ts file looks something like this.

import { Pipe, PipeTransform } from '@angular/core';
import {DomSanitizer, SafeResourceUrl} from "@angular/platform-browser";

@Pipe({
  name: 'youtubeSafeUrl'
})
export class YoutubePipe implements PipeTransform {

  constructor(private sanitizer: DomSanitizer){

  }

  transform(videoId: string): SafeResourceUrl {
    return this.sanitizer.bypassSecurityTrustResourceUrl(
      `https://www.youtube.com/embed/${videoId}`);
  }

}

Now the next step is to make an API call to the YouTube to retrieve the videos.
URL gonna look something like this

var finalURL = "https://www.googleapis.com/youtube/v3/search?key="+this.api+"&channelId="+this.chanId+"&part=snippet,id&order=date&maxResults="+this.result+"";

put your own
api = ‘yourapikey’;
chanId = ‘yourchannelid’;
result = 3; //how many videos you want to retrieve

I did it in my ngOnInit component life cycle hooks it looks some thing like this

 ngOnInit(){
    var finalURL = "https://www.googleapis.com/youtube/v3/search?key="+this.api+"&channelId="+this.chanId+"&part=snippet,id&order=date&maxResults="+this.result+"";
    console.log(finalURL);
    
     this.obser$ = this.http.get(finalURL).subscribe(response=>{
    
      console.log(response);
    
      let ytresults= response.json();
      console.log(ytresults);

      console.log(ytresults.nextPageToken);
      this.nextPageToken = ytresults.nextPageToken;
    
       ytresults.items.forEach(obj => {

           console.log(obj.id.videoId);
           this.ytvideolist.push(obj.id.videoId);
    
        });
      console.log(this.ytvideolist);  
        
 });
}

By looking at the code you might be now wondering about nextPageToken. When you make your first API call YouTube gives you nextPageToken here I am making use of that token to fetch subsequent YouTube videos If user wishes to see more videos on your site. For every request I am limiting my results to 3.

Now let’s display the videos in our WebPage

<div >
   <div *ngFor= "let videoId of ytvideolist" class="shadow1">
        <iframe [src]="videoId | youtubeSafeUrl" frameborder="0" allowfullscreen style="height:250px; width:350px"></iframe>
   </div>         
</div>  
 <button class="btn btn-primary" (click)="getNextVideos()">Next</button> 

Now as you can see we are filtering videoId with youtubeSafeUrl [src]=”videoId | youtubeSafeUrl” this job has taken care by our pipe.ts file.

on the subsequent requests we are calling the getNextVideos() function to retrieve next Videos.

Implementation of the getNextVideos() function looks something like this

getNextVideos(){
  
  //let relatedToVideoId = this.ytvideolist[2]; 
  var nextUrl="https://www.googleapis.com/youtube/v3/search?part=snippet&pageToken="+this.nextPageToken+"&maxResults="+this.result+"&channelId="+this.chanId+"&type=video&videoType=any&key="+this.api+"";
  ///var nextUrl = "https://www.googleapis.com/youtube/v3/videos?key="+this.API+"&channelId="+this.channelID+"&part=snippet,id&order=date&maxResults="+this.result+"&id="+relatedToVideoId+"";
  console.log(nextUrl);
  this.obser$ = this.http.get(nextUrl).subscribe(response=>{
    
      console.log(response);
    
      let ytresults= response.json();
      console.log(ytresults.nextPageToken);
      this.nextPageToken = ytresults.nextPageToken;
    
       ytresults.items.forEach(obj => {
          this.ytvideolist.push(obj.id.videoId);        
        });

      });       
}

I hope the blog helped you!

Fetch YouTube Videos Using YouTube Data API V3 In Angular 5!

Happy Coding ..!