$resource angular returning undefined with $promise
$resource angular returning undefined with $promise
我已经被困在这个相当一段时间了,现在不能弄清楚为什么值没有返回。我正在使用Angular $resource
向API发出GET请求。
我的$resource工厂是这样的:
.factory("Bookings", function ($resource) {
return $resource("www.example/bookings_on_date/:day", {});
})
我试图实现承诺,但不能正确地这样做。
function getBookings(day){
return Bookings.get({"day": day}).$promise.then(function(data) {
console.log(data.total)
return data.total;
});
}
$scope.todaysBookings = getBookings(TODAY);
$scope.tomorrowsBookings = getBookings(TOMORROW);
当我在控制台中查看console.log($scope.todaysBookings)
或$scope.tomorrowBookings
时,它返回undefined。
我也尝试了这个jsfiddle的所有东西,但不幸的是没有任何运气
我觉得应该是这样的:
function getBookings(day) {
return Bookings.get({"day": day}).$promise.then(function(data) {
return data.total;
});
}
getBookings(TODAY).then(function(total) {
$scope.todaysBookings = total;
});
getBookings(TOMORROW).then(function(total) {
$scope.tomorrowsBookings = total;
});
更新:我认为next代码风格可以帮助您防止next 扩展方法问题:
function getBookings(args) {
return Bookings.get(args).$promise;
}
getBookings({"day": TODAY}).then(function(data) {
$scope.todaysBookings = data.total;
});
getBookings({"day": TOMORROW}).then(function(data) {
$scope.tomorrowsBookings = data.total;
});
这里有一些优点:
- 传递对象到函数可以帮助您轻松地传递不同的方法中的参数和参数非常接近方法调用(a)有点容易读);
- 返回函数的完整响应能不能帮你处理不同的数据(方法能不能回放?不同的回应取决于不同的论点,但这不是好的做法
注。否则,可以像这样删除函数声明和代码(尽可能保持简单):
Bookings.get({"day": TODAY}).$promise.then(function(data) {
$scope.todaysBookings = data.total;
});
Bookings.get({"day": TOMORROW}).$promise.then(function(data) {
$scope.tomorrowsBookings = data.total;
});
相关文章:
- 使用promise和mongoose对文档进行排序
- Fighting with FRP
- issue with FB.Event.subscribe
- 测试Angular Service解决错误回调中的promise
- geolocation-marker.js conflict with markerclusterer.js
- Angular 2.0 with JavaScript or TypeScript?
- javascript singleton with promise
- Promise/A+ with chain then() 回调用例
- 如何在 Node JS FS 模块中使用 Typescript Async/ await with promise
- Chained Promise with Express:在最后一步中未收到任何数据
- Promise.all behavior with RxJS Observables?
- Jasmine Testing with Angular Promise 无法使用 TypeScript 解析
- NodeJS:在循环中使用 Promise with Q
- Javascript Q Promise Sequence Order with Arguments
- angularjs ng-show with promise expression
- Coffeescript Promise with Jquery Post
- AngularJS ui router $stateChangeStart with promise无限循环
- undefined with promise async / await
- ' fetch ', work with mode ' no-cors '不会调用promise.然后回调
- $resource angular returning undefined with $promise