创建一个新的angular $资源

时间:2015-09-22 16:40:03

标签: javascript angularjs angular-resource

我有一个页面,用于在我们的restful Web服务中创建新资源。该页面的控制器如下:

appController.controller('AddCtrl', ['$scope', 'Person',
        function($scope, $location, Person) {
    $scope.person = new Person();
    $scope.emailList = [];
    $scope.add = function() {
        $scope.emailList.push({email: $scope.email});
        $scope.person.emailList = $scope.emailList;
        $scope.person.$save();
    };
}]);

我的服务人员,看起来像这样:

appService.factory('Person', ['$resource',
    function($resource, uuid){
        return $resource(baseUrl + 'candidate/:uuid', {}, {
            query: {method:'GET', isArray:true},
            get: {method:'GET', params:{uuid: uuid}},
            save: {method: 'POST'},
            remove: {method: 'DELETE', params:{uuid: uuid}}
        });
    }
]);

但是,当我查看该页面时,我注意到该行的错误:

$scope.person = new Person();

Person is not a function at new <anonymous> ...

我不确定为什么这是一个问题。之前工作正常。我还尝试在服务中添加一个create方法:

appService.factory('Person', ['$resource',
    function($resource, uuid){
        var r = $resource(baseUrl + 'candidate/:uuid', {}, {
            ...
        });
        r.create = function() {
            return $resource(baseUrl + 'candidate', {});
        }
        return r;
    }
]);

但是,我在控制器中收到以下错误:

$scope.person = Person.create();

TypeError: Cannot read property 'create' of undefined at new <anonymous>

1 个答案:

答案 0 :(得分:2)

原因是,经常发生,而不是你在寻找它。问题出在这里:

appController.controller('AddCtrl', ['$scope', 'Person',
    function($scope, $location, Person) {

您已为控制器指定了两个依赖项,但您的函数需要3个参数 - 最后一个将为空,您的Person服务被指定为$location。它应该是:

appController.controller('AddCtrl', ['$scope', '$location', 'Person',
    function($scope, $location, Person) {

假设您正在使用$ location。

您的资源中会出现相同的问题 - uuid始终为null。

相关问题