2014-11-23 46 views
4

我有一個返回承諾的服務。我想檢查返回的值是否爲空對象。我怎樣才能做到這一點。我想我需要以某種方式從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 

我可以檢查預期的屬性時,對象不是空的,而是想要一個更通用的方法。

+0

你嘗試'如果(!data.length)' – charlietfl 2014-11-23 21:45:05

+0

@charlietfl - 返回undefined是否有數據。 – cyberwombat 2014-11-23 22:57:42

回答

0

解開返回值,可以直接訪問的承諾:

Auth.identify() 
    .$promise 
    .then(function(data) { 
     if (!_.isEmpty(data)) { 
     // ... 
     } 
    }); 
+0

Nope - 數據仍然是一個資源對象,其屬性與我的帖子一樣。 – cyberwombat 2014-11-24 00:56:04

0

你是如此接近。你不應該叫響應「數據」時,它實際上是一個資源對象,它看起來很像您發佈的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 
    } 
});