Last active
November 16, 2017 13:12
-
-
Save jdnichollsc/7367fe5b17369e856157 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 hidden or 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 hidden or 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 hidden or 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")); | |
} | |
} | |
}); |
Is a pleasure 👍
how to send a some data from controller to the service to include it as a params ?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you, this is really helpful.