如何使用Controller和Service在AngularJS中发出PUT请求?

时间:2017-04-04 12:22:07

标签: angularjs angular-resource

我有一个与NodeJS API交互的AngularJS Web APP。 我需要使用任务对象向API发出一些http请求(CRUD操作)。

现在我尝试向本地网址发送PUT请求:

http://localhost:4000/tasks/:id/finish

我在视图中有一个按钮,它触发控制器上的一个函数(在这种情况下,vm.finish),它向服务(TaskService.finish(id))发出请求。

视图

    <md-card ng-repeat="task in vm.unfinishedTasks">
        <md-card-header ui-sref="main.edit({id: task.id})" class="md-title">
            {{ task.title }}
        </md-card-header>
        <md-card-title>
            {{ task.description }}
        </md-card-title>
        <md-card-actions layout="row" layout-align="center">
            <md-button ng-click="vm.delete(task.id)"><md-icon>close</md-icon></md-button>
            <md-button><md-icon>{{task.priorityClass}}</md-icon></md-button>
            <md-button ng-click="vm.finish(task.id)"><md-icon>done</md-icon></md-button>
        </md-card-actions>
    </md-card>

控制器

function TasksListCtrl(TaskService, toastr, $http, $state, $promise) {

        var vm = this;
        ...

        vm.finish = function (id) {
                console.log("Calling the service to finish the task...");
                TaskService.finish(id)
                    .$promise.then(
                        function (response) {
                            toastr.success('Task finished.');
                            $state.reload();
                        },
                        function (err) {
                            toastr.error('There was a problem when trying to finish the task. Please refresh the page before trying again.')
                        }
                    )
        }

服务

function TaskService($resource) {

        //The API runs locally for now. 
        var apiUrl = 'http://localhost:4000/tasks';
        var resource = $resource(apiUrl);;
        return {
            unfinishedTasks: $resource(apiUrl, {}, {
                query: {
                    method: 'GET',
                    params: {
                        finished: false
                    },
                    isArray: true
                }
            }),
            finishedTasks: $resource(apiUrl, {}, {
                query: {
                    method: 'GET',
                    params: {
                        finished: true
                    },
                    isArray: true
                }
            }),
            save: function (taskDto) {
                return resource.save(taskDto);
            },
            finish: function (id) {
                console.log('Finishing the task...')
                return $resource(apiUrl + '/:id/finish', {
                    id: '@id'
                }, {
                    'finish': {
                        method: 'PUT',
                        params: {
                            id: "@id"
                        }
                    }
                });
            },
            delete: function (id) {
                return particularResource.delete();
            }
        }

console.log消息按预期显示,但PUT请求根本没有显示。在这种情况下,如何正确编码PUT请求?什么是调用服务功能的正确方法?

当我尝试从服务中调用结束功能时出现控制台错误

Calling the service to finish the task...
Finishing the task...
angular.js:14525 TypeError: Cannot read property 'then' of undefined
    at TasksListCtrl.vm.finish (TasksListCtrl.js:42)
    at fn (eval at compile (angular.js:15358), <anonymous>:4:274)
    at callback (angular.js:26994)
    at Scope.$eval (angular.js:18161)
    at Scope.$apply (angular.js:18261)
    at HTMLButtonElement.<anonymous> (angular.js:26999)
    at defaultHandlerWrapper (angular.js:3734)
    at HTMLButtonElement.eventHandler (angular.js:3722)

3 个答案:

答案 0 :(得分:0)

尝试使用$ http

$http.put(url, newTaskObject).then(successFn, errorFn);

答案 1 :(得分:0)

所以,我决定使用$ http而不是$ resource。解决方案完美无缺。我的代码就像这样。

<强>控制器

vm.delete = function (id) {
         TaskService.delete(id)
             .then(
                 function (response) {
                     toastr.success('Task succesfully deleted.');
                     $state.reload();
                    },
                 function (err) {
                     toastr.error('There was a problem in the deletion. Please refresh the page before trying again.')
                 }
             )
     }

<强>服务

function TaskService($http) {

    //The API runs locally for now. 
    var apiUrl = 'http://localhost:4000/tasks';
    return {
        unfinishedTasks: function () {
            return $http.get(apiUrl, {
                params: {
                    "finished": false
                }
            });

        },
        finishedTasks: function () {
            return $http.get(apiUrl, {
                params: {
                    "finished": true
                }
            });
        },
        save: function (taskDto) {
            return $http.post(apiUrl,taskDto);
        },
        finish: function (id) {
            return $http.put(apiUrl + '/' + id + '/finish', null);
        },
        delete: function (id) {
            return $http.delete(apiUrl + '/' + id);
        }
    }
}

只有一个细节:流控制在控制器层实现,而不是在服务层实现。

感谢您的建议。

答案 2 :(得分:0)

我们必须使用名称&#39; finish&#39;来调用2个方法。首先是服务方法&#39;完成&#39;另一种是ng-resource方法&#39; finish&#39;。 调用方法完成如下:

TaskService.finish(id).finish(id)
.$promise.then(
    function (response) {
        toastr.success('Task finished.');
        $state.reload();
    },
    function (err) {
        toastr.error('There was a problem when trying to finish the task. Please refresh the page before trying again.')
    });