我尝试使用Restangular从后端检索JSON对象。
1)这很好用,但我不知道如何处理错误,因为没有回调/保证功能:
meals = restAngular.all('meal').getList({date: selectedDate}).$object;
以下承诺不起作用:
restAngular.all('meal').getList({date: selectedDate}).then(function(newMeals){
console.log(newMeals);
meals = newMeals;
});
我在我的" newMeals"中得到了一个Restangular对象。对象而不是我的Json对象。 类似的东西:
addRestangularMethod: function (){var g=arguments,h=a?u:this; all: function () { [native code] } allUrl: function () { [native code] } clone: function () { [native code] } customDELETE: function () { [native code] } etc..
如何使用承诺并能够处理潜在错误来获取我的JSON"餐食"
2)补充问题:自Angularjs 1.2及其更好的新$资源实施以来,Restangular仍然是一个不错的选择吗?
非常感谢
答案 0 :(得分:7)
您可以这样做:
restAngular.all('meal').getList({date: selectedDate}).then(function(newMeals){
console.log(newMeals);
meals = newMeals;
}, function(response) {
console.log("Error with status code", response.status);
});
答案 1 :(得分:1)
获取简单回复对象
// using .plain() method
restAngular.all('meal').getList({date: selectedDate}).then(function(newMeals) {
console.log(newMeals); // prints restangular object, ie, your response object with additional methods like get, post, put, remove, clone and many others
// To get plain response
meals = newMeals.plain();
console.log(meals); // prints plain response object
})
.catch(function(response) {
console.log("Error with status code", response.status);
});
,否则强>
// you can configure this globally in restangular config by adding below line of code
// so that you will get plain response data by default
restAngular.setPlainByDefault(true);
// and now
restAngular.all('meal').getList({date: selectedDate}).then(function(newMeals) {
console.log(newMeals); // prints plain object since setPlainByDefault is set to true in restangular config
meals = newMeals;
})
.catch(function(response) {
console.log("Error with status code", response.status);
});
请参阅documentation了解详情