$ resource成功回调返回$ promise [英] $resource success callback returning $promise
问题描述
使用Angular 1.2.14,$ resource的成功回调应该返回一个对象,但有时会得到一个$ promise.node/express Web服务返回null,但是Angular将其解释为$ promise.从Web服务返回非null时,成功回调将按预期方式获取对象.
Using Angular 1.2.14, $resource's success callback should return an object, but it sometimes gets a $promise. The node/express web service is returning null, but Angular interprets it as a $promise. When a non-null is returned from the web service, the success callback gets the object as expected.
$resource('/api/users/:userId/team').get({ userId: userId }, function(team) {
console.log('team: ', team);
}, function(err) {
console.log('err: ', err);
});
team的值(成功回调的参数)为:
The value of team (the parameter to the success callback) is:
$promise: Object
catch: function (callback) {
finally: function (callback) {
then: function (callback, errback, progressback) {
__proto__: Object
$resolved: true
__proto__: Resource
$delete: function (params, success, error) {
$get: function (params, success, error) {
$query: function (params, success, error) {
$remove: function (params, success, error) {
$save: function (params, success, error) {
constructor: function Resource(value) {
__proto__: Object
为什么成功回调获得$ promise而不是对象?
Why is the success callback getting a $promise and not an object?
推荐答案
为什么成功回调获得$ promise而不是对象?
Why is the success callback getting a $promise and not an object?
因为它发出了成功的HTTP请求并收到了一个响应,而该响应恰巧是 null
.返回 null
并不是我们向HTTP服务器发送信号通知我们值无效的方式-而是,我们返回适当的状态码来指示失败-请参见
Because it made a successful HTTP request and received a response which happened to be null
. Returning null
is not how we signal to an HTTP server that our value is invalid - rather, we return the appropriate status code to indicate failure - see this article.
如何从客户端修复它?
How do I fix it from the client?
嗯,您没有问这个,但是我认为这是您真正关心的,因为 $ resource
返回一个Promise,您可以自己通过例如装饰器对其进行转换.
Well, you didn't ask this, but I assume this is what you actually care about, since $resource
returns a promise, you can transform it yourself, via a decorator for example.
如果您不需要可重用性,则只需执行以下操作:
If you don't need re-usability you can simply do:
$resource('/api/users/:userId/team').get({ userId: userId }).then(function(res){
if(res === null) return $q.reject("Error, server returned null");
return res;
}).then(function(team) {
console.log('team: ', team);
}, function(err) {
console.log('err: ', err);
});
否则,您可以将其包装为更通用的方法:
Otherwise, you can wrap it in a more general method:
function notNull(prom){
return prom.then(function(res){
if(res === null) return $q.reject("Error, got null);
return res;
});
};
哪个会让你做:
notNull($resource('/api/users/:userId/team').get({ userId: userId })).then(function(res){
// server returned not null.
}).catch(function(e){
// returned null, or other server error, or error in previous then handler.
});
这篇关于$ resource成功回调返回$ promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!