1

I keep getting the following error:

Cannot read property 'get' of undefined
    at Object.getChannelIdFromYoutubeUsername
    at Object.vm.creatorAccountCreationFormSubmit

Even though I am injecting $http into my service, and whenever I paste the url being passed into the $http.get command, I get an output in my browser window.

Here is my service:

angular.module('adsomaApp').service('YoutubeService', function($log) {

  var url = 'https://www.googleapis.com/youtube/v3';

  function getChannelIdFromYoutubeUsername(youtubeApi, youtubeUsername, $http) {
    var queryUrl = url + "/channels/?key=" + youtubeApi + "&forUsername=" + youtubeUsername + "&part=id";
    return ($http.get(queryUrl).then(handleSuccess, handleError));
  }

  function handleSuccess(response) {
    return response.data;
  }

  function handleError(response) {
    if (!angular.isObject(response.data) || !response.data.message) {
      return ($q.reject('An unknown error occurred.'));
    }
    return ($q.reject(response.data.message));
  }

  var youtubeService = {
    getChannelIdFromYoutubeUsername: getChannelIdFromYoutubeUsername
  };
  return youtubeService;
});

Here is my controller:

vm.channelId = {};

vm.creatorAccountCreationFormSubmit = function() {
  YoutubeService.getChannelIdFromYoutubeUsername(ConstantsService.youtubeSettings().youtubeApiKey, vm.connectYoutubeFormData.youtubeUsername).then(function(succ) {
    vm.channelId = succ;
    $log.info(vm.channelId);
  }, function error(err) {
    $log.error('Error: ', err);
  });
};
methuselah
  • 12,766
  • 47
  • 165
  • 315

2 Answers2

2
angular.module('adsomaApp').service('YoutubeService', function($log, $http) { }

you didn't inject in service layer so it is showing undefin

Sangram Badi
  • 4,054
  • 9
  • 45
  • 78
1

Two basic changes:

Inject $http into the Service

angular.module('adsomaApp').service('YoutubeService', function($http, $log) {

Remove $http from the arguments of this service method

function getChannelIdFromYoutubeUsername(youtubeApi, youtubeUsername) {

The issue is that, when this Service Method is being called from the Controller, the third argument is NOT sent by you. Which, basically means, $http will be null. I have addressed this issue by injecting $http in the service and by excluding the third argument in the method signature.

These two changes should take care of the issue. I have not included rest of the code.

Rangamannar
  • 174
  • 4