我创建了一个资源对象:
factory('TextResource',
function($resource) {
return $resource(adminBaseUrl+'/texts/:type', {}, {
create: {method: 'POST', params: {type:'create'}, headers: {'Content-Type':'application/x-www-form-urlencoded'}},
update: {method: 'POST', params: {type:'update'}, headers: {'Content-Type':'application/x-www-form-urlencoded'}},
query: {method: 'GET', params: {type: 'list'}},
remove: {method: 'POST', params: {type: 'remove'}, headers: {'Content-Type':'application/x-www-form-urlencoded'}},
getText: {method: 'GET', params: {type: 'get', id:'@id'}}
});
}
)
我的控制器是:
controller('EditText', ['$scope', '$location', '$routeParams', 'TextResource', 'HttpStatusMessage',
function($scope, $location, $routeParams, TextResource, HttpStatusMessage) {
$scope.alerts = [];
$scope.languages = [];
TextResource.getText(
{id: $routeParams.id},
function(data) {
$scope.languages = data.result;
},
function(error) {
var httpError = new HttpStatusMessage(error.status);
$scope.alerts.push({type:'error', msg:httpError.msg});
});
$scope.closeAlert = function(index) {
$scope.alerts.splice(index, 1);
}
$scope.submit = function() {
TextResource.update(
$scope.languages,
function(data) {
if( data.type == 'success' ) {
$location.path('texts');
} else {
$scope.alerts.push({type:data.type, msg:data.message});
}
},
function(error) {
var httpError = new HttpStatusMessage(error.status);
$scope.alerts.push({type:'error', msg:httpError.msg});
});
}
$scope.cancel = function() {
$location.path('texts');
}
}
])
我从TextResource.getText请求获得的响应是:
{"result":[{"id":"3","value":"This is my first text<br>","key":"my_first_text","language_id":"1","name":"English"},{"id":"3","value":"Ceci est mon premier texte","key":"my_first_text","language_id":"3","name":"French"}],"num_rows":2}
现在,当我点击提交时,它会显示错误:
Error: a.push is not a function
响应对象包含2个键结果,num_rows结果是一个数组。我没有在资源对象中使用isArray参数的原因是万一在服务器中发生任何错误,如会话超时,访问不允许等等。服务器返回一个对象包含错误消息。
答案 0 :(得分:1)
通过修改更新功能解决问题,如:
$scope.submit = function() {
TextResource.update(
{'language':$scope.languages},
function(data) {
if( data.type == 'success' ) {
$location.path('texts');
} else {
$scope.alerts.push({type:data.type, msg:data.message});
}
},
function(error) {
var httpError = new HttpStatusMessage(error.status);
$scope.alerts.push({type:'error', msg:httpError.msg});
});
}
我在更新中直接发布了一个抛出错误的数组。因此封装在另一个密钥中解决了这个问题。