当我在自定义服务中封装$ http服务时,我得到自定义方法未定义错误

时间:2015-01-29 12:22:16

标签: angularjs angularjs-service

我是AngularJS的新手,我正在尝试创建自定义服务来封装$ http服务。我已经尝试过调试但无法修复此问题。你能告诉我这里做错了吗?自定义服务中的函数返回一个promise。我认为问题在那里。当我用console.log替换getUser代码时,它并没有给出未定义的'错误。

    <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
"

这可能非常简单。但我无法发现自己​​的错误。它在网上工作。如有任何指示,将不胜感激。感谢。

2 个答案:

答案 0 :(得分:1)

忽略了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]);
}());`

`

答案 1 :(得分:0)

你犯了几个错误,

通过这种方式调用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;        
    });
}]);