AngularJS如何处理异步调用

时间:2012-11-09 07:48:59

标签: javascript angularjs

var todoApp = angular.module('TodoApp', ['ngResource']);
todoApp.value('restTodo', 'api/1/todo/:id');

var todoCtrl = todoApp.controller('TodoCtrl', function($scope, $resource, restTodo) {
    $scope.src = $resource(restTodo);
    //add & refresh
    $scope.src.save({ content: 'hello world', done: false });
    $scope.todos = $scope.src.get();
    //OR
    //delete & refresh
    $scope.src.delete({ id: '1' });
    $scope.todos = $scope.src.get();
});

当我添加/删除项目并再次从服务器读取待办事项列表以刷新它时。我发现我会不时地发现这个错误:

System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.

有人说我可以将MultipleActiveResultSets=true;放入连接字符串,但我怀疑它只会隐藏我的问题,因为GET显然是在DELETE完成其工作之前尝试进行脏读。

在基于事件的样式语言中,我会在DELETEComplete()事件后自然地调用GET。但是,我是AngularJS的新手,我不知道这是怎么做到的?请帮忙。

1 个答案:

答案 0 :(得分:2)

我不是专家,但我会将读取的代码放在save的成功回调中。像这样:

var todoApp = angular.module('TodoApp', ['ngResource']);
todoApp.value('restTodo', 'api/1/todo/:id');

var todoCtrl = todoApp.controller('TodoCtrl', function($scope, $resource, restTodo) {
    $scope.src = $resource(restTodo);
    //add & refresh
    $scope.src.save({ content: 'hello world', done: false }, 
      function(data) {
       $scope.todos = $scope.src.get();
    });
});