gapi.client.youtube is undefined?

怎甘沉沦 提交于 2019-11-27 23:21:03

The problem is that the gapi.client.load method takes a bit of time to complete, and it is asynchronous, so your page (which you've set up to be synchronous) is going on and running the searchA() method before the youtube library is fully loaded. There are two ways around this. One is to use the callback argument of the load method, like this:

<html>
<body>
 <script>
        function googleApiClientReady(){
                gapi.client.setApiKey('AIzaSyARvwirFktEIi_BTaKcCi9Ja-m3IEJYIRk');
                gapi.client.load('youtube', 'v3', function() {
                        searchA();
                });
        }
        function searchA() {
                var q = 'pink floyd';
                var request = gapi.client.youtube.channels.list({
                        part: 'statistics',
                        forUsername : 'GameSprout'
                });
                request.execute(function(response) {
                        var str = JSON.stringify(response.result);
                        alert(str);
                });
        }
 </script>

If you'd prefer, you could also wrap a promise around the loading callback:

<html>
<body>
    <script>
        googleApiClientReady=function() {
          loadApi() = function() {
                return new Promise(function(resolve,reject){
                        gapi.client.setApiKey('AIzaSyARvwirFktEIi_BTaKcCi9Ja-m3IEJYIRk');
                        gapi.client.load('youtube', 'v3', resolve);
                });
          };
          loadApi().then(function() {
                var q = 'pink floyd';
                var request = gapi.client.youtube.channels.list({
                        part: 'statistics',
                        forUsername : 'GameSprout'
                });
                request.execute(function(response) {
                        var str = JSON.stringify(response.result);
                        alert(str);
                });
          });
        };
</script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
</body>
</html>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!