Jason Christa
Jason Christa

Reputation: 12508

AngularJS Inconsistent Data After Saving

I have a user profile form where a user can change there name and upload a profile picture. After they save their data they are taken back to the home page where their profile information is shown in the sidebar.

The problem is sometimes the GET request to populate the User resource is made before the back-end is done processing the POST request that updated the User resource. Is there any good solution to this problem?

The relevant controller code:

$scope.user.$save();
$location.path('/');

Upvotes: 0

Views: 74

Answers (1)

dave
dave

Reputation: 64677

From the Angular docs:

The action methods on the class object or instance object can be invoked with the following parameters:

HTTP GET "class" actions: Resource.action([parameters], [success], [error])

non-GET "class" actions: Resource.action([parameters], postData, [success], [error])

non-GET instance actions: instance.$action([parameters], [success], [error])

Success callback is called with (value, responseHeaders) arguments. Error callback is called with (httpResponse) argument.

So you would have to do:

$scope.user.$save({}, function(data,headers) {
    //success
    $location.path('/');
}, function(response) {
    //error       
    alert("error")         
});

Or

$scope.user.$save({}, {}, function(data,headers) {
    //success
    $location.path('/');
}, function(response) {
    //error       
    alert("error")         
});

I'm not sure which is classified as a "class action" - I assume user is an instance but I'm not positive.

If you want to update the info in the sidebar, you could broadcast that the post has finished:

$rootScope.$broadcast('user:saved')

and do whatever logic you need to in the sidebar

//in your sidebar controller or wherever
$scope.$on('user:saved', function() {

});

Upvotes: 1

Related Questions