自定义角度服务出错:无法读取属性

时间:2015-05-16 04:01:34

标签: angularjs angularjs-service

以下是plnkr链接。我创建了一个自定义的Angular服务,但它无法正常工作。我得到的错误在于:

TypeError: Cannot read property 'then' of undefined

演示在这里:http://plnkr.co/edit/Jae0nymkg6wyZYPBvmao?p=preview

我的代码如下:

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();
});

感谢。

1 个答案:

答案 0 :(得分:0)

在服务中使用这种方法。已经在使用然后在服务中。再次使用控制器..所以它可能会有问题

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