Tom
Tom

Reputation: 16276

AngularJS how to handle async calls

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

When I add/delete item(s) and read the todo list from server again to refresh it. I find that I will hit this error from time to time:

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

Someone said I can put MultipleActiveResultSets=true; into connect string, but I suspect it will only hide my issue, because the GET is obviously trying to have a dirty read before DELETE can finish its job.

In event based style language, I will naturally call GET after a DELETEComplete() event. However, I am new to AngularJS, I am not sure how it is done here? Please help.

Upvotes: 2

Views: 384

Answers (1)

JvdBerg
JvdBerg

Reputation: 21866

I am not a expert, but I would place the read code in the success callback of the save. Something like this:

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

Upvotes: 2

Related Questions