Restangular put() not working on multiple put()'s

不问归期 提交于 2019-12-13 17:53:12

问题


Here is the code in question

function putCategory(category) {
        console.log(category.parent_id);
        category.put().then(function (data) {
            console.log(data.parent_id);
            delete category._updating;
            angular.extend(category, data);
            updateCategories();
        }, function (error) {
            delete category._updating;
            category.errors = readError(error);
        });
    }

Here is a brief example of the problem:

  • initial state: parent_id = null (it is a root category)
  • change the parent_id to 1, and call putCategory.
  • The category updates properly (parent_id = 1).
  • Decide that I want parent_id to be 2 instead. Call putCategory again.
  • The category does not update, and stays in the same state (parent_id = 1). No further updates seem to stick.
  • If I refresh the page, parent_id is still 1. So at least the first put() worked
  • I can then make another change, and it will work, but a second (or third etc) will not. So I can change it back to null, or to 2, but any additional change will not work unless I refresh it again. Basically get 1 proper put request per object per page load.

When I inspect the console logs, the input data is correct (the first console log), and the second console log is correct the first time, and wrong the second time (and later).

When I look at the network tab, I can see that the outgoing params are also correct the first time, and wrong in the second.

So as best I can tell, the put() call is not working properly, does anyone have any idea why?


回答1:


Restangular does some tricky things with the this binding of the elements (see Copying elements for another problematic scenario). The problem is most likely in your call angular.extend(category, data);. This call copies all enumerable properties (including Restangular methods), while it would be enough to update the fields (e.g. id, name, date) of the element.

The most easy solution for this is to use the plain() function of your response. This function returns the pure data object you received, so you can use it to copy exclusively your data fields.

category.put().then(function (data) {
            console.log(data.parent_id);
            delete category._updating;
            angular.extend(category, data.plain());
            updateCategories();
        });


来源:https://stackoverflow.com/questions/29570897/restangular-put-not-working-on-multiple-puts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!