-
-
Save Rakonda/68f171709f1fcbea13c9 to your computer and use it in GitHub Desktop.
Service with Angular.js in Ionic Framework to get Products from Web Service or Local Storage using Promises and ngCordova
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var app = angular.module('demo', ['ionic', 'ngCordova', 'demo.controllers', 'demo.services']); | |
var controllers = angular.module('demo.controllers', []); | |
var services = angular.module('demo.services', []); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
controllers.controller('ProductsController', ['$scope', 'Products', '$ionicPopup', function ($scope, Products, $ionicPopup) { | |
$scope.products = []; | |
Products.getProducts().then(function (products) { | |
$scope.products = products; | |
}, function (error) { | |
$ionicPopup.alert({ | |
title: 'Warning', | |
template: error | |
}); | |
}); | |
} ]); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
services.factory('Products', function ($http, $q, $cordovaNetwork) { | |
return { | |
getProducts: function () { | |
var deferred = $q.defer(); | |
var isOnline = false; | |
try { | |
isOnline = $cordovaNetwork.isOnline(); | |
} | |
catch (e) { // For debugging in the browser | |
isOnline = true; | |
} | |
var self = this; | |
if (isOnline) { | |
$http.get("http://www.nicholls.co/mywebservice/products").then(function (response) { | |
self.setProducts(response.data); | |
return deferred.resolve(response.data); | |
}, function () { | |
return deferred.reject('Error communicating with the server'); | |
}); | |
} else { | |
var products = self.getProductsFromLocal(); | |
if (products) { | |
deferred.resolve(products); | |
} else { | |
return deferred.reject('You need to connect to internet for get products'); | |
} | |
} | |
return deferred.promise; | |
}, | |
setProducts: function (products) { | |
window.localStorage.setItem("products", angular.toJson(products)); | |
}, | |
getProductsFromLocal: function(){ | |
return angular.fromJson(window.localStorage.getItem("products")); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment