繁体   English   中英

如何在AngularJS的许多控制器上仅使用一个$ http请求

[英]How to use an only one $http request on many controllers in AngularJS

我有一个名为app.js的文件,在那里,我为Web应用程序使用了许多控制器。 我的问题是我多次重复相同的代码。 例如,此$ http POST

 $http({
        method: 'POST',
        url: urlProfile,
        data: $.param($scope.ProfileForm),
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-Token': '\UsernameToken Token="' + mycookie + '"',
        }
    }).success(function(data, status, headers, config) {
        $scope.showProfiles();
        $('#newProfile').modal('hide');
        $scope.notifications(
            $scope.title = 'Notificación',
            $scope.body = 'Se ha creado un nuevo perfil',
            $scope.icon = '/img/restore.png'
        );
    }).error(function(data, status, headers, config) {
        alert('No se ha guardado el Perfil con el nombre: ' + profilename);
    });

如何在控制器中使用Service o Factory之类的方法,而仅提供URL或Method之类的参数

创建自己的工厂并返回promise对象:

(function(){
    angular.module('test', []);

    angular.module('test')
        .controller('Controller1', ['$scope', 'myService', function($scope, myService){
            myService.myRequest(URL, $.param($scope.ProfileForm)).then(function(result){
                //result of ajax here, do your scope manipulation here
            });
        }])
        .controller('Controller2', ['$scope', 'myService', function(myService){
            myService.myRequest(URL, $.param($scope.ProfileForm)).then(function(result){
                //result of ajax here, do your scope manipulation here
            });
        }])
        .factory('myService', ['$http', function($http){
            return {
                myRequest: function(urlProfile, data){
                    return $http({
                        method: 'POST',
                        url: urlProfile,
                        data: data,
                        headers: {
                            'Accept': 'application/json',
                            'Content-Type': 'application/x-www-form-urlencoded',
                            'X-Token': '\UsernameToken Token="' + mycookie + '"',
                        }
                    }).then(function(result){
                        return result.data;
                    });
                }
            };
        }]);
})();

我建议遵循JohnPapa的样式指南 它是模块化的,可帮助您分离问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM