检查角度资源响应是否为空
问题描述:
我有一个返回承诺的服务。我想检查返回的值是否为空对象。我怎样才能做到这一点。我想我需要以某种方式从promise对象中提取返回的值。检查角度资源响应是否为空
这里是我的资源:
app.factory('Auth', ['$resource',
function($resource) {
return $resource('/user/identify', {}, {
identify: {
url: '/user/identify'
},
});
}
]);
然后在服务:
Auth.identify(function(data) {
// This always passes since data contains promise propeties
if (!_.isEmpty(data)) {
}
});
数据的控制台登录给出:
Resource
$promise: Object
$resolved: true
__proto__: Resource
我可以检查预期的属性时,对象不是空的,而是想要一个更通用的方法。
答
解开返回值,可以直接访问的承诺:
Auth.identify()
.$promise
.then(function(data) {
if (!_.isEmpty(data)) {
// ...
}
});
+0
Nope - 数据仍然是一个资源对象,其属性与我的帖子一样。 – cyberwombat 2014-11-24 00:56:04
答
你是如此接近。你不应该叫响应“数据”时,它实际上是一个资源对象,它看起来很像您发布的Resource
对象:
$resource('/api/...').get({...}).then(function(response) {
if (response.data) {
// the response has a data field!
}
}
// note: this is using query(), which expects an array
$resource('/api/...').query({...}).then(function(response) {
if (response.length > 0) {
// the response data is embedded in the response array
}
});
你尝试'如果(!data.length)' – charlietfl 2014-11-23 21:45:05
@charlietfl - 返回undefined是否有数据。 – cyberwombat 2014-11-23 22:57:42