Skip to content Skip to sidebar Skip to footer

Get All Youtube Videos In A Playlist Using Angular Js

I want to get all of the YouTube videos in a specified playlist. The API currently allows you to pull 50 records at a time but you can pull the next set of records by passing a nex

Solution 1:

You need to use the pageToken attribute to fetch the next page.

From the documentation, Use the nextPageToken attribute from the api response.Call the API one or more times to retrieve all items in the list. As long as the API response returns a nextPageToken, there are still more items to retrieve.

In your controller, define a local variable nextPageToken to retrieve the next page and call the getPlaylistVideos with the nextPageToken attribute recursively until all the results are retrieved.

app.controller('ctrl', ['$http', '$scope', 'youtubeService', function ($http, $scope, youtubeService) {

        // define a local variable pageToken, it is gonna be undefined for the first time and will be initialized with next page token after subsequent responses$scope.nextPageToken;
        $scope.playlistVideos = [];

        youtubeService.getPlaylists('UC-9-kyTW8ZkZNDHQJ6FgpwQ').then(function (response) {
            $scope.$apply(function () {
                $scope.playlists = response.items;
            });
        });

        $scope.getPlaylistVideos = function (selection) {
            // pass the nextPageToken attribute to the getPlaylistVideos method.
            youtubeService.getPlaylistVideos(selection.id, $scope.nextPageToken).then(function (response) {
                $scope.$apply(function () {
                    $scope.playlistVideos.push(response.items);

                    if(typeof response.nextPageToken != 'undefined'){
                          $scope.nextPageToken = response.nextPageToken;
                          // call the get playlist function again$scope.getPlaylistVideos(selection);
                    } 
                });
            });
        }

        $scope.getVideos = function (selection) {
            youtubeService.getVideos(selection).then(function (response) {
                $scope.$apply(function () {
                    $scope.videos = response.items;
                });
            });
        }
}]);

In your service, pass the pageToken attribute to the api to fetch the next page.

functiongetPlaylistVideos(playlistId, pageToken) {
...
     // pass the page token as a parameter to the API
     $.get('https://www.googleapis.com/youtube/v3/playlistItems', { part: 'snippet', maxResults: 50, playlistId: playlistId, key: key, pageToken: pageToken })
...
}

Post a Comment for "Get All Youtube Videos In A Playlist Using Angular Js"