Я получаю ошибку пользовательского метода undefined, когда я инкапсулирую службу $http в пользовательскую службу

Я новичок в AngularJS и пытаюсь создать собственный сервис для инкапсуляции сервиса $http. Я пробовал отладку, но не могу это исправить. Не могли бы вы сказать, что я делаю неправильно здесь. Функция в пользовательской службе возвращает обещание. Я думаю, что проблема в этом. Когда я заменяю код getUser на console.log, он не дает «неопределенной» ошибки.

    <html ng-app="gitHubViewer">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <script src="../angular.min.js"></script>
    <script src="search.js"></script>
    <script src="github.js"></script>

    <style>
  .my-input {
    color:black;
    background: red;
  }
</style>
</head>
<body ng-controller="MainController">
<div>
{{error}}
</div>
<h1><label>{{message}}</label></h1>
<label> {{countdown}}</label>
<form name="searchUserForm" ng-submit="search(username)">
    <input type="search" required placeholder="Enter User Name" ng-model="username"/>
    <input type="submit" value="Search"/>
</form>
<div ng-include="'userDetails.html'" ng-show="user"></div> 
</body>
</html>

Контроллер:

(function(){
    var app = angular.module("gitHubViewer",[]);
    var MainController = function(
        $scope,github,$interval,$log,
        $location,$anchorScroll
        ){

        var decrementCountdown = function() {
            $scope.countdown--;
            if($scope.countdown<1)
                $scope.search($scope.username);
        };
        var onResultComplete = function(data) {
            $scope.user=data;
            github.getRepos($scope.user).then(onRepos,onError);
        };

        var onRepos = function(data) {
            $scope.repos = data;
            $location.hash("userDetails");
            $anchorScroll();
        };
        var onError = function(reason) {
            $scope.error ="Could not fetch data";
        };

        var countDownInterval = null;
        var startCountdown = function() {
            countDownInterval= $interval(decrementCountdown,1000,$scope.countdown);
        };

        $scope.search = function(username) {
            $log.info("Searching for "+username);
            github.getUser(username).then(onResultComplete,onError);
            if(countDownInterval) {
                $interval.cancel(countDownInterval);
                $scope.countdown = null;
            }
        };

        $scope.username="angular";
        $scope.message="Git Hub Viewer";
        $scope.orderReposByStar="-stargazers_count";
        $scope.countdown = 5;
        startCountdown();

    };
    app.controller('MainController',["$scope","github","$interval","$log","$location","$anchorScroll",MainController]);
}());

Пользовательский сервис:

(function(){

var github = function($http) {

        var getUser = function(username) {
            console.log("in github "+username);
            $http.get("https://api.github.com/users/"+username).
            then( function(response){
                return response.data;    //it would return the data wrapped in a promise as the call 
                        //to 'then' returns a promise
            });
        };


        var getRepos = function(user) {
            $http.get(user.repos_url).
            then(function(response){
                return response.data;   
            });
        };

        return {
            getUser: getUser,
            getRepos: getRepos
        };

    };
    var module = angular.module("gitHubViewer"); 
        module.factory("github" ,["$http", github]);
}());

Ошибка:

"Error: github.getUser(...) is undefined
MainController/$scope.search@file:///home/smitha/AngularJS/DirectivesAndViews2WriteOwnService/search.js:34:4
MainController/decrementCountdown@file:///home/smitha/AngularJS/DirectivesAndViews2WriteOwnService/search.js:11:5
fd/g.prototype.notify/<@file:///home/smitha/AngularJS/angular.min.js:115:162
Pe/this.$get</l.prototype.$eval@file:///home/smitha/AngularJS/angular.min.js:126:189
Pe/this.$get</l.prototype.$digest@file:///home/smitha/AngularJS/angular.min.js:123:278
Pe/this.$get</l.prototype.$apply@file:///home/smitha/AngularJS/angular.min.js:126:469
e/O.$$intervalId<@file:///home/smitha/AngularJS/angular.min.js:91:100
"

Это может быть что-то очень простое. Но я не могу заметить свою ошибку. Это работало в онлайн-турориале. Был бы признателен за любые указатели. Спасибо.


person Smitha    schedule 29.01.2015    source источник
comment
пожалуйста, на вашем контроллере попробуйте console.log(github) и посмотрите, не определено ли оно также   -  person Fedaykin    schedule 29.01.2015
comment
Я попробовал то, что вы сказали. Это не неопределенно. Дал следующий вывод: Object { getUser: github/getUser(), getRepos: github/getRepos() } Это означает, что служба предоставляет getUser и getRepos без параметров. Спасибо за указатель   -  person Smitha    schedule 29.01.2015


Ответы (2)


Пропустил возврат из функций в сервисе gitHub. Отсюда и неопределенная ошибка. Исправленный код выглядит следующим образом: github.js

(function(){

var github = function($http) {

        var getUser = function(username) {
            console.log("in github "+username);
            return $http.get("https://api.github.com/users/"+username).
            then( function(response){
                return response.data;    

            });
        };


        var getRepos = function(user) {
            return $http.get(user.repos_url).
            then(function(response){
                return response.data;   
            });
        };

        return {
            getUser: getUser,
            getRepos: getRepos
        };

    };
    var module = angular.module("gitHubViewer"); 
        module.factory("github" ,["$http", github]);
}());`

`

person Smitha    schedule 29.01.2015

ты сделал несколько ошибок,

вызов getuser таким образом

 github.getUser(username).then(onResultComplete,onError);

Значит это :

  • Служба github возвращает функцию getUser, которая принимает один параметр
  • Функция getUser возвращает некоторый метод, который имеет функцию .then

но эта доза зависимостей не представлена ​​в вашей реализации службы


поэтому вам нужно изменить свой сервис на что-то подобное

angular.module('myApp.services', [])
  .factory('githubService', ['$http', function($http) {

    var doRequest = function(username, path) {
      return $http({
        method: 'JSONP',
        url: 'https://api.github.com/users/' + username + '/' + path + '?callback=JSON_CALLBACK'
      });
    }
    return {
      events: function(username) { return doRequest(username, 'events'); },
    };
  }]);

и использовать его так

app.controller('ServiceController', ['$scope', 'githubService',
    function($scope, githubService) {
            // uses the $http service to call the GitHub API
            // and returns the resulting promise
      githubService.events(newUsername)
        .success(function(data, status, headers) {
                    // the success function wraps the response in data
                    // so we need to call data.data to fetch the raw data
          $scope.events = data.data;        
    });
}]);
person Ahmed Adel    schedule 29.01.2015
comment
Увидев ваш комментарий, я понял, что getUser и getRepos ничего не возвращают. Я новичок в функциональном программировании, поэтому предположил, что возврат в «затем» возвращает данные из getUser. Я добавил возврат, и теперь он работает. Спасибо за указатели - person Smitha; 30.01.2015
comment
Добро пожаловать, отметьте это как ответ, чтобы помочь другим людям, у которых была такая же проблема. - person Ahmed Adel; 31.01.2015