3

I just start to using angularjs and I want to display youtube thumbnail image from the youtube video url ... is there a way to display video thumbnail when people insert url in input and then click the button,

PLUNKER

http://plnkr.co/edit/9SBbTaDONuNXvOQ7lkWe?p=preview

5 Answers 5

3

Youtube provide default thumbnail image of its video.

You can use below sample URL to create thumbnail image.

http://img.youtube.com/vi/<insert-youtube-video-id-here>/default.jpg

Where you need to search id from the given url & create url like above will give you thumbnail image.

Controller

app.controller('MyCtrl', ['$scope',
  function($scope) {
    $scope.inputs = [];

    $scope.addInput = function() {
      $scope.inputs.push({
        field: ''
      });
    }

    $scope.removeInput = function(index) {
      $scope.inputs.splice(index, 1);
    }

    $scope.set2 = function($ayd) {
      var thumb = getParameterByName(this.input.ayd, 'v'),
        url = 'http://img.youtube.com/vi/' + thumb + '/default.jpg';
      this.thumb = url
    }

    function getParameterByName(url, name) {
      name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
      var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(url);
      return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }
  }
]);

There many ways to do this, you can refer from here

Working Plunkr Here

Sign up to request clarification or add additional context in comments.

5 Comments

thank you very much it works like a charm ,,,, can I also use vimeo with same input???
@AydIn don;t sure vimeo has such feature or not
or can I display the youtube video and vimeo video instead of the image? like in iframe
yes you could do that..eaisly..to get good UI controller you should go for some plugin
a better whay is to use the official API of YouTube. Imagine one day they change the url of the image...
2

Here is a simple Plunker that pulls the Youtube ID from the inputted URL with a filter and then applies the image url to the image source using the Youtube provided image paths.

app.js

var app = angular.module('plunker', []);


app.filter('getVideoId', function() {
    return function(input) {

     // get video id
     var output = input.substr(input.indexOf("=") + 1);

     return output;
   }
})

index.html

<body>
    <div>
      <input type="text" ng-model="input.url" placeholder="Youtube URL" />
      <img class="ythumb" ng-src="http://img.youtube.com/vi/{{input.url | getVideoId}}/0.jpg"/>
    </div>

2 Comments

if I want to use vimeo too how can I use with this?
You would have to use the Vimeo API. It isn't as easy as Youtube.
2

With AngularJS

  • First, you need to creat a project in console.google.developers.
  • Enable the API YouTube API V3 (set to on).
  • In credential part, creat a public access key.

In the controller VideoCtrl for example:

'use strict';

function init() {
    window.initGapi(); // Calls the init function defined on the window
}

angular.module('team')
    .service('googleService', ['$http', '$q', function ($http, $q) {

        var deferred = $q.defer();
        this.googleApiClientReady = function () {
            gapi.client.setApiKey('YOUR API KEY');
            gapi.client.load('youtube', 'v3', function() {
                var request = gapi.client.youtube.playlistItems.list({
                    part: 'snippet',
                    playlistId: 'PLila01eYiSBjOtR8oqXkY0i5c1QS6k2Mu',
                    maxResults: 8
                });
                request.execute(function(response) {
                    deferred.resolve(response.result);
                });
            });
            return deferred.promise;
        };
    }])
    .controller('VideosCtrl', function ($scope, $window, $sce, googleService) {

        $window.initGapi = function() {
            $scope.$apply($scope.getChannel);
        };

        $scope.getChannel = function () {
            googleService.googleApiClientReady().then(function (data) {
                $scope.channel = data;
            }, function (error) {
                console.log('Failed: ' + error)
            });
        };
    });

And don't forget to init the API. Add this line at the end of your index.html

<script src="https://apis.google.com/js/client.js?onload=init"></script>

For beginners you may be interested by this answer: https://stackoverflow.com/a/25783421/2274530

Comments

1

this works for me :D

<video>
  <source [src]="yourvideo.mp4">
</video>

Comments

0
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
const YOUTUBE_API_KEY = 'abcd--z';
const YOUTUBE_API_URL = 'https://www.googleapis.com/youtube/v3/search';

class

export class VideoDetail {
  id: string;
  title: string;
  description: string;
  thumbnailUrl: string;
  videoUrl: string;

  constructor(obj?: any) {
      this.id = obj && obj.id || null;
      this.title = obj && obj.title || null;
      this.description = obj && obj.description || null;
      this.thumbnailUrl = obj && obj.thumbnailUrl || null;
      this.videoUrl = obj && obj.videoUrl || `https://www.youtube.com/watch?v=${this.id}`;
  }
}

component

@Component({
  selector: 'app-video-listing',
  templateUrl: './video-listing.component.html',
  styleUrls: ['./video-listing.component.scss']
})
export class VideoListingComponent implements OnInit {

  constructor(private http: HttpClient) {}
  ngOnInit()
  {
    // bpLmn-oO60E is the videoId of video
    this.search("bpLmn-oO60E").subscribe((data)=>{
      console.log(data);
    });
  }
  search(query: string): Observable<VideoDetail[]> {
    const params: string = [
      `q=${query}`,
      `key=${YOUTUBE_API_KEY}`,
      `part=snippet`,
      `type=video`,
      `maxResults=10`
    ].join('&');

    const queryUrl = `${YOUTUBE_API_URL}?${params}`;

    return this.http.get(queryUrl).pipe(map(response => {
      return response['items'].map(item => {
        return new VideoDetail({
          id: item.id.videoId,
          title: item.snippet.title,
          description: item.snippet.description,
          thumbnailUrl: item.snippet.thumbnails.high.url
        });
      });
    }));
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.