0

I have an application with Angularjs and Coldfusion. I have a form with some http queries for populating drop-down list. When the session server is out, I retrieve the status from the server, I display a dialog box (thanks to ngDialog) and I reload the page.(status 0 sent by the server because the server tries to reload an external authentication system before going on the main page of the application - not in the scope of this topic).

Here my code:

app.controller('ctrlAddContacts', function ($scope, $route, ContactService, ngDialog, $timeout){

    ContactService.getCountry().success(function(countries){
        $scope.countries = countries;       
    }); 

    ContactService.loadCategory('undefined',0).success(function(categories, status, header, config){
        $scope.categories = categories;
        console.log("status:" + status);        
    })
    .error(function (data, status, header, config) {
        console.log("sessionExpired: " + sessionExpired);
        console.log("ERROR ");
        console.log("data: " + data);
        console.log("status:" + status);
        console.log("header: " + header);
        console.log("config: " + config);
               if (status==0) {
                    alert("Your session expired - The page needs to be reloaded.\nPlease note that data enter in the form will be lost");        

                    // NGDIALOG BOX

                        var dialog = ngDialog.open({
                            template: '<p>Your session expired - The page needs to be reloaded.<br />Please note that data enter in the form will be lost</p>',
                            plain: true,
                            closeByDocument: false,
                            closeByEscape: false
                        });
                        setTimeout(function () {
                            dialog.close();
                            window.location = "http://myapp/index.cfm?#/add-contacts";      
                        }, 4000);


                }                   
    }).finally(function() {
      console.log("finally finished repos");
    }); 

});

It's working but I have to do that for each ajax HTTP request.

Here I have to do the same for:

   ContactService.getCountry().success(function(countries){
        $scope.countries = countries;      
    }); 

Thus I wouldd like to simplify the code in order to avoid to repeat the line, could you tell me please if I can do that and how (directive or factory for instance)?

Thanks

2 Answers 2

0

You can use service to handle all $http in your controllers, in this sample i try to connect controller and service by using $q to pass response from service result is dialog will handle in the service also you can get the response in your controller.

var app = angular.module("app", []);

app.controller("ctrl", function ($scope, service) {
    service.get('getCountry').then(function (data) {
        console.log(data);
    })
})

app.service("service", function ($http, $q, ContactService, ngDialog, $timeout) {
    this.get = function (api) {
        var deferred = $q.defer();

        //we used angular 1.6 => use then instead success
        ContactService[api]().then(function (response) {
            deferred.resolve(response.data);
        }, function (error) {
            if (error.status == 0) {
                alert("Your session expired - The page needs to be reloaded.\nPlease note that data enter in the form will be lost");
                var dialog = ngDialog.open({
                    template: '<p>Your session expired - The page needs to be reloaded.<br />Please note that data enter in the form will be lost</p>',
                    plain: true,
                    closeByDocument: false,
                    closeByEscape: false
                });
                $timeout(function () {
                    dialog.close();
                    window.location = "http://myapp/index.cfm?#/add-contacts";
                }, 4000);
            } else {
                alert("status is " + error.status);
            }
        })

        return deferred.promise;
    }
})
Sign up to request clarification or add additional context in comments.

Comments

0

You can use interceptors for this,

.factory('myInterceptor', ['$q', '$location', '$injector', function ($q, $location, $injector) {
    return {
        response: function (response) {
            if (response.status === 0) {
                console.log('http 0 response')
            }
            return response || $q.when(response);
        },
        responseError: function (rejection) {
            return $q.reject(rejection);
        }
    }
}])
.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push('myInterceptor');
}]);

Also interceptors can be used for global error handling, authentication, or any kind of synchronous or asynchronous pre-processing of request or postprocessing of responses.

Comments

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.