Search code examples
angularjsangularjs-service

Error in Custom Angular Service: Cannot read property


Below is the plnkr link. I have created a custom Angular service, but it's not working. The error I'm getting is here:

TypeError: Cannot read property 'then' of undefined

A demo is here: http://plnkr.co/edit/Jae0nymkg6wyZYPBvmao?p=preview

My code is below:

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

app.controller('mainCtrl', function(
  $scope, github, $interval,
  $log, $anchorScroll, $location) {

  $scope.message = "hi";

  var usercomplete = function(data) {
    $scope.user = data;
    github.getRepos($scope.user).then(Repository, onerror);

  };


  var Repository = function(data) {
    $scope.repos = data;
    $location.hash("userDetails");
    $anchorScroll();
  };

  var onerror = function(reason) {
    $scope.error = 'Could not fetch the data';

  };


  var decrement = function() {
    $scope.countdown -= 1;
    if ($scope.countdown < 1) {
      $scope.search($scope.username);
    }
  };

  var countDownInterval = null;
  var startCountDown = function() {
    countDownInterval = $interval(decrement, 1000, $scope.countdown);

  };


  $scope.search = function(username) {
    github.getUser(username).then(usercomplete, onerror);
    if (countDownInterval) {
      $interval.cancel(countDownInterval);
      $scope.countdown = null;
    }


  };



  $scope.username = 'Angular';
  $scope.repoSortOrder = "-stargazer_count";
  $scope.countdown = 5;
  startCountDown();
});

Thanks.


Solution

  • use this type of method in service. already your using then in service. again using controller.. so it may take problem

    var getUser = function(username) {
                return $http.get('https://api.github.com/users/' + username)
                .success(function (response) {
                    return response.data;
                }).error(function (err) {
                    return err;
                });
            };