$资源回调(错误和成功) [英] $resource callback (error and success)
问题描述
I'm使用AngularJS 1.1.3使用与承诺的新的$资源...
I´m using AngularJS 1.1.3 to use the new $resource with promises...
我怎样才能得到回调?
我试图以同样的方式我$ HTTP所做的:
How can I get the callback from that? I tried the same way I did with $http :
$resource.get('...').
success(function(data, status) {
alert(data);
}).
error(function(data, status) {
alert((status);
});
但没有'成功'既不是'错误'的功能...
But there is no 'success' neither 'error' functions...
我也试过了:
$resource.get({ id: 10 },function (data) {
console.log('success, got data: ', data);
}, function (err) {
alert('request failed');
});
这总是打印的成功,得到了数据即使返回的是一个 404 ...
That always print "success, got data" even if the return is a 404 ...
任何想法?
感谢
推荐答案
作为 PR上angulars的资源 和1.2角,角将切换到执行成功/错误检查的一个简单的方法。而不是附加回调或$则方法,无论是Resource.get(..)和instance.get()将支持$诺方法,这自然会返回为一个承诺。
As of a PR on angulars resource and angular 1.2, angular will be switching to a simpler way of performing success / error checking. Instead of attaching callbacks or a $then method, both the Resource.get(..) and instance.get() will support the $promise method, which naturally returns a promise for both.
由于角1.2的$承诺的功能还会去住:<一href=\"https://github.com/angular/angular.js/commit/05772e15fbecfdc63d4977e2e8839d8b95d6a92d\">$promise更改
As of angular 1.2 the $promise feature will go live: $promise changes
改变你的得到的要求是东西沿着这些路线(原来的例子是angularjs.org头版):
Change your "get" request to be something along these lines (original example is on angularjs.org front page):
factory('Project', function($resource) {
var Project = $resource('https://api.mongolab.com/api/1/databases' +
'/youraccount/collections/projects/:id',
{ apiKey: 'yourAPIKey' }, {
update: { method: 'PUT' }
}
);
Project.prototype.update = function(cb) {
return Project.update({id: this._id.$oid})
.$promise.then(
//success
function( value ){/*Do something with value*/},
//error
function( error ){/*Do something with error*/}
)
};
Project.prototype.destroy = function(cb) {
return Project.remove({id: this._id.$oid})
.$promise.then(
//success
function( value ){/*Do something with value*/},
//error
function( error ){/*Do something with error*/}
)
};
return Project;
});
在其他地方,在一个控制器可能实例化一个资源项目例如,你可以使用的成功和错误相同的接口:
Somewhere else in the a controller you may instantiate a resource "Project" instance where you can use the same interface for successes and errors:
var myProject = new Project();
myProject.$get({id: 123}).
.$promise.then(
//success
function( value ){/*Do something with value*/},
//error
function( error ){/*Do something with error*/}
)
这篇关于$资源回调(错误和成功)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!