AngularJS Factory $ http无法读取undefined的属性'length'

时间:2014-11-06 15:19:47

标签: javascript angularjs

我想为我的REST控制器使用一个工厂,它返回一个字符串数组。我想在我的services.js中重用该函数。

这是我的HTML(自动填充输入字段)

<input type="text" ng-model="vertrag.vertrag.v00Lobcode.lobCode" typeahead-wait-ms="1000"
typeahead="lobcode for lobcode in getLobcode($viewValue)" typeahead-loading="loadingLobcodes">

控制器

 $scope.getLobcode = function(val) {
    Autocomplete.get(val).then(function(promise) {
        console.log(promise);
    });
};

services.js

AppServices.factory('Autocomplete', function($http, API_URL) {
return {
    get: function(val) {
        var promise = $http.get(API_URL+'/leistobjekts/autocomplete/'+val.toUpperCase())
            .then(function(response) {
                return response.data;
        });
        return promise;
    }
};

});

我的例外

TypeError: Cannot read property 'length' of undefined
at http://localhost:8080/bootstrap/js/ui-bootstrap-tpls-0.11.0.js:3553:24
at deferred.promise.then.wrappedCallback (http://localhost:8080/js/lib/angular/angular.js:11498:81)
at deferred.promise.then.wrappedCallback (http://localhost:8080/js/lib/angular/angular.js:11498:81)
at http://localhost:8080/js/lib/angular/angular.js:11584:26
at Scope.$get.Scope.$eval (http://localhost:8080/js/lib/angular/angular.js:12608:28)
at Scope.$get.Scope.$digest (http://localhost:8080/js/lib/angular/angular.js:12420:31)
at Scope.$get.Scope.$apply (http://localhost:8080/js/lib/angular/angular.js:12712:24)
at http://localhost:8080/js/lib/angular/angular.js:14220:36
at completeOutstandingRequest (http://localhost:8080/js/lib/angular/angular.js:4349:10)
at http://localhost:8080/js/lib/angular/angular.js:4650:7 

实际上我得到了我需要的正确结果(控制台),但错误表明任何事情都无法正常工作。并且自动填充功能没有显示任何内容。

这是我的自动完成功能,已经为我工作了。但它不是真的可重复使用。

$scope.getLobcode = function(val) {
    return $http({
        method: "GET",
        url: API_URL+'/leistobjekts/autocomplete/'+val.toUpperCase(),
        cache:true

    }).then(function(res){
        console.log(res.data);
        var lobcodes = [];
        angular.forEach(res.data, function(item){
            lobcodes.push(item);
        });
          return lobcodes;
        });
};

提前致谢。

1 个答案:

答案 0 :(得分:2)

像这样回复你的承诺:

$scope.getLobcode = function(val) {
    return Autocomplete.get(val);
};

或只是这样做:

$scope.getLobcode = Autocomplete.get;