I want to simulate an async db operation in AngularJs. ( via setTimeout
).
I have this factory function code :( jsbin ) which uses an internal array
:
shoppingModule.factory('Items', function() {
var items = {};
items.query = function() {
// In real apps, we'd pull this data from the server...
return [
{title: 'Paint pots', description: 'Pots full of paint', price: 3.95},
{title: 'Polka dots', description: 'Dots with polka', price: 2.95},
{title: 'Pebbles', description: 'Just little rocks', price: 6.95}
];
};
return items;
});
The controller
, in turn calls :
function ShoppingController($scope, Items) {
$scope.items = Items.query();
}
But I want to simulate the return of data as async operation via setTimeout
operation. ( in short - I want to add non-blocking delay)
what have I tried ?
I tried to use $timeout
variable without any success., also tried to use setTimeout without success (cuz I didnt had $scope
object inside the method.)
Question :
how can I add setTimeout( 3 sec to simulate db operation) into the factory function ?
You can achieve this using promises. Modify your code to use something like this:
Factory:
var deferred = $q.defer();
$timeout(function () {
var returnObj = [
{title: 'Paint pots', description: 'Pots full of paint', price: 3.95},
{title: 'Polka dots', description: 'Dots with polka', price: 2.95},
{title: 'Pebbles', description: 'Just little rocks', price: 6.95}
];
deferred.resolve(returnObj);
}, 3000);
return deferred.promise;
And then just call it like this from the controller:
$scope.items = Items.query().then(function(res){
alert(res);
// successfully resolved
}, function(err) {
// handle errors
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.