如何使用angularJS从JSON url获取数据

时间:2016-07-07 04:24:30

标签: javascript angularjs json angularjs-directive

**这是我的service.js文件。这段代码无法正常工作有什么不对。以及如何创建服务文件。此链接将使用产品执行类别列表。该方案是单击我需要显示产品的类别。 **

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;
        }
    }
});

2 个答案:

答案 0 :(得分:1)

我更喜欢这种服务编码模式。我创建并使用了一个缓存服务,以便我们可以从任何工厂端点调用url并仍然可以获取它。

随意根据需要更改缓存时间。请参阅我关于搜索员工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;
    }])

然后你会像你这样在你的控制器中调用该服务

controller.js

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

答案 1 :(得分:0)

试试这个

.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;
            });
        }
    }
});

您正在使用Promise。在这些情况下,您不需要设置自己的承诺,因为您可以将作为$http.get的一部分返回的承诺链接起来