Not getting updated values after call to AngularJS $save

旧时模样 提交于 2019-12-24 16:18:06

问题


Folks, I am using AngularJS and angular-resource to perform a pretty simple REST API call. Here is my JavaScript code for a page that lists (and creates) messages:

(function() {
'use strict';
var messagesApp = angular.module('messagesApp', ['ngResource']);

messagesApp.factory('Message', function($resource) {
    return $resource('/api/messages/:id', {id: '@id'}, {
        query: {method:'GET', isArray:true} });
});

messagesApp.controller('MessagesCtrl',
  function($scope, Message) {
    $scope.messages = Message.query();

    $scope.addMessage = function() {
        $.Dialog({
            'title': 'Add new Message',
            'content': '<p>Enter the <strong>unique</strong> name of the new message.</p><input type="text" id="newMessageName"/><p>Enter the <strong>unique</strong> ID for this message.</p><input type="text" id="newID"/>',
            'draggable': false,
            'overlay': true,
            'closeButton': true,
            'buttonsAlign': 'right',
            'buttons': {
                'save': {
                    'action' : function() {
                        var newMessage = new Message();
                        newMessage.name = $('#newMessageName').val()
                        newMessage.altid= parseInt($('#newID').val())
                        newMessage.longDescription = "This is a new message";
                        newMessage.$save();
                        console.log(newMessage.id)
                    }
                }
            }
        });
    }
  }
);
})();

What happens is the console log message prints out 'undefined'. When I look at the network log, I see that my REST API is indeed returning the newly created object when it comes back.. Should I not be using Ok as a result type and instead use something else? Is there an HTTP header I'm missing .. or am I using the $save thing wrong??

The $.Dialog() method comes from another JavaScript library I'm using (metroui.og.ua) and I don't know if that's interfering with this or not..


回答1:


newMessage.$save() is asynchronous, so if you want to get a hold of the response data you should do it in the success callback function:

newMessage.$save(function(msg, headers){
  console.log(newMessage.id); // note, at this point msg === newMessage
});

See the docs



来源:https://stackoverflow.com/questions/16866265/not-getting-updated-values-after-call-to-angularjs-save

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