How do I make an AngularJS $resource update after a POST, PUT, or DELETE request?

All we need is an easy explanation of the problem, so here it is.

In my Angular app, I’ve setup “project” as a $resource. In my controller, I ask the server for the data over a GET request immediately when the page loads. I can edit the information in my browser using Angular’s two-way data binding, and then I can save the data back to the server via a POST request, like this:

(edited/simplified for brevity)

function ProjectCtrl($scope, $routeParams, Project) {
    $scope.project = Project.get({id: $routeParams.projectId},
        function(data) { //Successfully received data }, 
        function(data) { //Failed to receive data },
    );

    $scope.saveProject = function() {
        $scope.project.save();
    };
}

My Node server correctly receives the data, processes it and makes some changes, saves it to my database, and then responds with the newly updated “project” object via JSON. Angular does not display the new object until I refresh the page. Is there any way to make it display the new data? I’m assuming there’s a more automatic Angular way to do this than to manually call another GET request after $scope.project.save();

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

It looks like the server response comes back as the first argument to the callback to save, so as long as the server responds with the full object data, you should be able to use it to create a “new” Project object like this:

function ProjectCtrl($scope, $routeParams, Project) {
    $scope.project = Project.get({id: $routeParams.projectId},
        function(data) { /* Successfully received data */ }, 
        function(data) { /* Failed to receive data */ },
    );

    $scope.saveProject = function() {
        $scope.project.save(function(data) {
            $scope.project = new Project(data);
        });
    };
}

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply