0

**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;
        }
    }
});
3
  • what is the purpose of return $http.get('localhost/youtubewebservice/shop-categorylist-product.php'), and where employees come from. Commented Jul 7, 2016 at 4:41
  • This is my another question. can you give me answer for this. Thank you !!! stackoverflow.com/questions/37107684/… Commented Jul 7, 2016 at 4:44
  • You may want to study a bit more about how promises work in JS, and about Using Services to Share Data Between Controllers in Angular Commented Jul 7, 2016 at 4:56

2 Answers 2

1

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;
            });
        }
    ]);
Sign up to request clarification or add additional context in comments.

3 Comments

hard to tell without a full plunkr of your project, but this should do what you want.. it's the format i use for my controllers and services in my angular projects. The exception being that you're calling findAll() and then filtering the result when someone calls any other subquery in EmployeeService rather than having an intelligent API endpoint that only returns the relevant data. 6 of one, half a dozen of the other as to who does the lifting i suppose (does kind of break with most API standards though IMO)
can you give some answer for this question dear. stackoverflow.com/questions/37107684/…
I dont know this your answer worked or not. But I will give you more points for you. because, I had big problem you gave me some answer. There fore I respect to you "haxxxton". Good job.
0

try this

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

    var get = function(){return $http.get('http://localhost/youtubewebservice/shop-categorylist-product.php')}

    return {
        findAll: function() {
            return get();
        },

        findById: function(employeeId) {
            return get().then(function(employees){
                var employee = employees[employeeId - 1];
                return employee;
            });

        },

        findByName: function(searchKey) {
            return get().then(function(employees){

                var results = employees.filter(function(element) {
                    var fullName = element.firstName + " " + element.lastName;
                    return fullName.toLowerCase().indexOf(searchKey.toLowerCase()) > -1;
                });

                return results;
        },

        findByManager: function (managerId) {
            return get().then(function(employees){
                results = employees.filter(function (element) {
                    return parseInt(managerId) === element.managerId;
                });
                return results;
            });
        }
    }
});

You are using promises incorrectly. You do not need to setup your own promise in these cases as you can chain off the promise that is returned as a part of $http.get

3 Comments

can you give me answer for this question. Thank you stackoverflow.com/questions/37107684/…
[$injector:unpr] Unknown provider: categoryProvider <- category <- HomeController ......... This is error
The error looks totally unrelated. It looks related to a category service the controller is expecting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.