0

Looking at a RESTful CRUD SPA with angularjs for example.

When using the RESTful approach with Angularjs, I am running into cases where an update/delete/etc. isn't reflected in the list without a hard refresh (F5). It's occurring because the save/update/delete are taking longer than JavaScript takes to run the next command which should update the list.

app.controller('UserDetailCtrl', ['$scope', '$routeParams', 'UserFactory', '$location',
function ($scope, $routeParams, UserFactory, $location) {

    // callback for ng-click 'updateUser':
    $scope.updateUser = function () {
        UserFactory.update($scope.user);  // Before this is done
        $location.path('/user-list');     // this has already fetched the (outdated) list
    };

Coming from e.g. .NET MVC where in a situation like this I would return the List of items from the update (return value). The scaffolded Web API controller is RESTful, and it doesn't return anything from POST, PUT, or DELETE.

    // DELETE api/<controller>/5
    public **void** Delete(int id)
    {
        // delete...
    }

In Angularjs I could imagine a couple approaches to ensure that the List of users is always up to date. (For example maintain a list in the $scope and modify it simultaneously with the POST/PUT/DELETE calls but it seems cumbersome)

What is the best approach in Angularjs using RESTful style to ensure e.g. a list has the accurate up to date data? If there isn't a general approach, what would be the best way to handle it in this example app.

2
  • Since the Web API controller is RESTful, it doesn't return anything from POST, PUT, or DELETE - Being RESTful is no reason not to return anything. Commented Sep 28, 2014 at 19:05
  • Thanks for the clarification, I guess that's just a Web API scaffolding default. Commented Sep 28, 2014 at 19:13

2 Answers 2

2

You could wait for the AJAX request to complete before changing the path:

UserFactory.update($scope.user, function() {
    $location.path('/user-list');
});
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, the callback. w3schools.com/jquery/jquery_callback.asp Fits perfectly!
0

In a scenario like this I have used the $http or $resource services.

Using $http you would redirect in the success callback

Using $resource you can redirect inside the promise .$promise.then

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.