Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

**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;
        }
    }
});
share|improve this question
    
what is the purpose of return $http.get('localhost/youtubewebservice/shop-categorylist-pro‌​duct.php'), and where employees come from. – Anupam Singh Jul 7 at 4:41
    
This is my another question. can you give me answer for this. Thank you !!! stackoverflow.com/questions/37107684/… – DRK Jul 7 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 – Italo Ayres Jul 7 at 4:56
up vote 1 down vote accepted

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;
            });
        }
    ]);
share|improve this answer
    
When I use this code. It will work ??? – DRK Jul 7 at 5:07
    
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) – haxxxton Jul 7 at 5:09
    
can you give some answer for this question dear. stackoverflow.com/questions/37107684/… – DRK Jul 7 at 5:11
    
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. – DRK Jul 7 at 5:13

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

share|improve this answer
    
can you give me answer for this question. Thank you stackoverflow.com/questions/37107684/… – DRK Jul 7 at 5:32
    
This code not working – DRK Jul 11 at 10:12
    
what is the error – swestner Jul 11 at 15:53
    
[$injector:unpr] Unknown provider: categoryProvider <- category <- HomeController ......... This is error – DRK Jul 12 at 4:17
    
The error looks totally unrelated. It looks related to a category service the controller is expecting. – swestner Jul 12 at 13:54

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.