我已经创建了一个角度服务来与PHP制作的简单REST服务器进行对话。我可以看到我能够获得单个记录,所有记录的列表,并添加新记录,但是,在添加新记录后,我遇到了从服务器获取正确响应以便能够对其进行操作的问题。
我知道它正在工作,因为新记录正在添加,但是,如果由于某种原因请求不起作用,我希望为用户发送通知,等等......
这是服务:
angular.module('adminApp.services', ['ngResource'])
.factory('Settings', function($resource) {
return $resource('rest/setting/:id', {id: '@id'}, {
'query' : { method: 'GET', params: {}, format: 'json', isArray: true },
'save' : { method: 'POST', params: {}, format: 'json', isArray: true },
'get' : { method: 'GET', params: {}, format: 'json', isArray: false },
'update': { method: 'PUT', params: {id: '@id'}, format: 'json', isArray: true },
'delete': { method: 'DELETE', params: {id: '@id'}, format: 'json', isArray: false }
});
});
作为控制器的一部分,我有以下内容:
$scope.save = function() {
var result = Settings.save({}, $scope.settings);
console.log(result);
// Here I would like to send the result to the dialog
// to determine wether or not the request was successful
// dialog.close(result);
};
来自HTTP请求的网络响应,通过javascript控制台返回从服务器返回的'true',但是,console.log(result)返回'true'中的字符数组 - 我猜对了是因为'save'中的isArray:true选项是必要的,因为params作为数组被发送到服务器:
[$promise: Object, $resolved: false]
0: "t",
1: "r",
2: "u",
3: "e",
$promise: Object,
// I tried passing result.$resolved to the dialog,
// but if yousee above it resolves to false up top first
$resolved: true,
length: 4,
__proto__: Array[0]
我知道HTTP响应是一个json值为true,如果我可以挂钩它会很容易(我来自jQuery背景,也许我做错了,我已经明确地从这里删除了jQuery)项目,以免它阻止我的学习)。
我想问题是,我如何从服务器实际获得我可以实际使用的JS变量的响应?
编辑:已更新
我将服务改为:
angular.module('adminApp.services', ['ngResource'])
.factory('Settings', function($http, $resource, $log) {
return $resource('rest/setting/:id', {id: '@id'}, {
save : {
method: 'POST',
params: {},
format: 'json',
isArray: true,
transformResponse: [function(data, headersGetter) {
$log.info(data); // returns true
return { response: data };
}].concat($http.defaults.transformResponse)
},
update : { method: 'PUT', params: {id: '@id'}, format: 'json', isArray: true },
delete : { method: 'DELETE', params: {id: '@id'}, format: 'json', isArray: false }
});
});
并呼吁:
$scope.save = function() {
$scope.results = Settings.save({}, $scope.settings);
console.log($scope.results); // Still returns the response with $promise
//dialog.close(true);
};
但我仍然没有得到回应