You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用$http时出现Cannot read property 'get' of undefined报错求助

问题排查与解决方案

嘿,我帮你揪出这个问题的根源了!你遇到的 Cannot read property 'get' of undefined 错误,核心原因是**$http 并没有被正确注入到你的 YoutubeService 服务中**。

看你提供的服务代码开头:

angular.module('adsomaApp').service('YoutubeService', function($log) { 
  var url = 'https://www.googleapis.com/youtube/v3'; 
  function getChannelIdFromYoutubeUser...

这里只注入了 $log,完全没把 $http 加入依赖列表,所以当你在 getChannelIdFromYoutubeUsername 里调用 $http.get() 时,$http 就是 undefined,自然会抛出这个错误。

修复步骤

  1. 给服务注入 $http
    修改服务的依赖注入部分,把 $http 加进去,同时确保要调用的方法被暴露给外部(比如控制器):

    angular.module('adsomaApp').service('YoutubeService', function($log, $http) { 
      var url = 'https://www.googleapis.com/youtube/v3'; 
    
      // 实现获取频道ID的方法
      function getChannelIdFromYoutubeUsername(username) {
        return $http.get(`${url}/channels`, {
          params: {
            part: 'id',
            forUsername: username,
            key: '你的Google API密钥' // 记得替换成你自己的有效密钥
          }
        }).then(function(response) {
          $log.debug('频道ID获取成功:', response.data);
          // 处理返回数据,提取频道ID
          return response.data.items?.[0]?.id || null;
        }).catch(function(error) {
          $log.error('频道ID获取失败:', error);
          throw error; // 把错误抛出去让上层处理
        });
      }
    
      // 暴露服务方法,让控制器能调用
      return {
        getChannelIdFromYoutubeUsername: getChannelIdFromYoutubeUsername
      };
    });
    
  2. 额外注意事项

    • 确保你的Google API密钥已经启用了 YouTube Data API v3,不然即使浏览器能访问URL,服务端调用也可能权限报错
    • 如果你的项目开启了严格依赖注入模式(比如用了 ngStrictDi),建议用数组式注入避免代码压缩后出错:
      angular.module('adsomaApp').service('YoutubeService', ['$log', '$http', function($log, $http) {
        // 服务代码...
      }]);
      
    • 检查调用该服务的控制器,确保 YoutubeService 已经被正确注入到控制器中

内容的提问来源于stack exchange,提问作者methuselah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:30:31