DRK DRK - 5 months ago 30
AngularJS Question

how to get data from JSON url using angularJS

**This is my service.js file. this code not working what is the wrong. And how to create service file. This links will execute category list with product. The scenario is when click on the category I need to show products. **

angular.module('directory.services', [])

.factory('EmployeeService', function($q) {

return $http.get('http://localhost/youtubewebservice/shop-categorylist-product.php')

return {
findAll: function() {
var deferred = $q.defer();
deferred.resolve(employees);
return deferred.promise;
},

findById: function(employeeId) {
var deferred = $q.defer();
var employee = employees[employeeId - 1];
deferred.resolve(employee);
return deferred.promise;
},

findByName: function(searchKey) {
var deferred = $q.defer();
var results = employees.filter(function(element) {
var fullName = element.firstName + " " + element.lastName;
return fullName.toLowerCase().indexOf(searchKey.toLowerCase()) > -1;
});
deferred.resolve(results);
return deferred.promise;
},

findByManager: function (managerId) {
var deferred = $q.defer(),
results = employees.filter(function (element) {
return parseInt(managerId) === element.managerId;
});
deferred.resolve(results);
return deferred.promise;
}
}
});

Answer

I prefer this coding pattern for services. I have created and used a Caching service so that we can make the call to the url from any of the factory endpoints and still have it fetch.

Feel free to change the cache time as required. And please see my notes about searching for an employee id

services.js

angular.module('directory.services', [])
    .factory('CacheSetter', ['$cacheFactory', function ($cacheFactory) {
        // create a cache factory to be used with $http requests
        var factory = {};
        factory.getCached = function (url) {
            var cache = $cacheFactory.get('$http');
            var urlCache = cache.get(url);
            if(urlCache){
                var now = new Date().getTime();
                if(urlCache[2]){
                    if(urlCache[2].date){
                        var cacheDate = new Date(urlCache[2].date).getTime();
                        if(now - cacheDate > 60 * 60 * 1000){ // 1 hour (change this as needed)
                            cache.remove(url);
                        }
                    }
                }
            }
            return true;
        }
        return factory;
    }])
    .factory('EmployeeService', ['$http', '$q', function ($http, $q) {
        var path = 'http://localhost/youtubewebservice/shop-categorylist-product.php';
        var factory = {};
        factory.findAll = function(){
            return $http.get(path, { cache: CacheSetter.getCached(path) }).then(function (employees) {
                return employees;
            }, function(reject){
                // your request was rejected (timeout, failed, etc.)
            });
        }
        factory.findById = function(employeeId){
            factory.findAll().then(function(employees){
                // i would suggest actually doing a loop to confirm employee id rather than this
                // method as it relies on employee ids always being sequential and being returned in order
                var employee = employees[employeeId - 1];
                return employee;
            });
        }
        factory.findByName = function(searchKey){
            factory.findAll().then(function(employees){
                var results = employees.filter(function(element) {
                    var fullName = element.firstName + " " + element.lastName;
                    return fullName.toLowerCase().indexOf(searchKey.toLowerCase()) > -1;
                });
                return results;
            });
        }
        factory.findByManager = function(managerId){
            factory.findAll().then(function(employees){
                var results = employees.filter(function (element) {
                    return parseInt(managerId) === element.managerId;
                });
                return results;
            });
        }
        return factory;
    }])

Then you would call the service in your controller like this

controller.js

angular.module('directory.controllers', [])
    .controller('categoryController', ['$scope', 'EmployeeService',
        function($scope, EmployeeService){
            $scope.employees = [];
            EmployeeService.findAll().then(function(employees){
                $scope.employees = employees;
            });
        }
    ]);