简体   繁体   中英

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

I have a file with the name app.js and there, I use many controllers for my web applications. My problem is I repeat many times the same code. For example this $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);
    });

How can I use this method like Service o Factory in my controllers and only provide the params like URL or Method

Create your own factory and return the promise object:

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

I recommend following JohnPapa's style-guide . It is modular and helps you separate your concerns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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