在自定义服务中封装 $http 服务时出现自定义方法未定义错误 [英] I get custom method undefined error when I encapsulate $http service in custom service

查看:27
本文介绍了在自定义服务中封装 $http 服务时出现自定义方法未定义错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 AngularJS 的新手,我正在尝试创建自定义服务来封装 $http 服务.我试过调试,但无法解决这个问题.你能告诉我我在这里做错了什么吗?自定义服务中的函数返回一个承诺.我认为问题就在那里.当我用 console.log 替换 getUser 代码时,它不会给出未定义"错误.

 <头><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><风格>.my-input {颜色:黑色;背景:红色;}</风格><body ng-controller="MainController"><div>{{错误}}

<h1><label>{{message}}</label></h1><标签>{{倒计时}}</label><form name="searchUserForm" ng-submit="search(username)"><input type="search" required placeholder="输入用户名" ng-model="username"/><input type="submit" value="搜索"/></表单><div ng-include="'userDetails.html'" ng-show="user"></div></html>

控制器:

(function(){var app = angular.module("gitHubViewer",[]);var MainController = 函数($scope,github,$interval,$log,$location,$anchorScroll){var decrementCountdown = 函数(){$scope.countdown--;如果($scope.countdown<1)$scope.search($scope.username);};var onResultComplete = 函数(数据){$scope.user=数据;github.getRepos($scope.user).then(onRepos,onError);};var onRepos = 函数(数据){$scope.repos = 数据;$location.hash("userDetails");$anchorScroll();};var onError = 函数(原因){$scope.error ="无法获取数据";};var countDownInterval = null;var startCountdown = 函数(){countDownInterval= $interval(decrementCountdown,1000,$scope.countdown);};$scope.search = 函数(用户名){$log.info("正在搜索"+用户名);github.getUser(username).then(onResultComplete,onError);如果(countDownInterval){$interval.cancel(countDownInterval);$scope.countdown = null;}};$scope.username="angular";$scope.message="Git Hub 查看器";$scope.orderReposByStar="-stargazers_count";$scope.countdown = 5;开始倒计时();};app.controller('MainController',["$scope","github","$interval","$log","$location","$anchorScroll",MainController]);}());

定制服务:

(function(){var github = 函数($http){var getUser = 函数(用户名){console.log("在github中"+用户名);$http.get("https://api.github.com/users/"+用户名).然后(功能(响应){返回 response.data;//它将返回包装在承诺中的数据作为调用//to 'then' 返回一个承诺});};var getRepos = 函数(用户){$http.get(user.repos_url).然后(功能(响应){返回 response.data;});};返回 {获取用户:获取用户,getRepos:getRepos};};var module = angular.module("gitHubViewer");module.factory("github" ,["$http", github]);}());

错误:

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

这可能很简单.但我无法发现我的错误.它适用于在线教程.将不胜感激任何指针.谢谢.

解决方案

忽略了 gitHub 服务中函数的返回.因此,未定义的错误.更正后的代码如下:github.js

(function(){var github = 函数($http){var getUser = 函数(用户名){console.log("在github中"+用户名);返回 $http.get("https://api.github.com/users/"+用户名).然后(功能(响应){返回 response.data;});};var getRepos = 函数(用户){返回 $http.get(user.repos_url).然后(功能(响应){返回 response.data;});};返回 {获取用户:获取用户,getRepos:getRepos};};var module = angular.module("gitHubViewer");module.factory("github" ,["$http", github]);}());`

`

I am new to AngularJS and I am trying to create custom service to encapsulate $http service. I have tried debugging but am not able to fix this. Could you please tell what am I doing wrong here. The function in the custom service returns a promise. I think the problem is there. When I replace the getUser code by console.log it doesn't give 'undefined' error.

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

Controller:

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

Custom Sevice:

(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:

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

It could be very something simple. But I am not able to spot my mistake. It worked in the online turorial. Would be grateful for any pointers. Thanks.

解决方案

Had overlooked return from the functions in the gitHub service. Hence the undefined error. The corrected code is as below: 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]);
}());`

`

这篇关于在自定义服务中封装 $http 服务时出现自定义方法未定义错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆