Categories
Uncategorized

How to set $http timeout in AngularJs

http://

Global Timeout
To set a global http timeout in angularjs, we need to use the following code, which takes time in milliseconds to override the default http timeout value.

angular.module('myApp',[])
  .factory('timeoutHttpIntercept', function ($rootScope, $q) {
    return {
      'request': function(config) {
        config.timeout = 1 * 60 * 1000; 
                      // 1 minute or 60 seconds or 60,000 milliseconds
       return config; } 
      }; 
    });

angular.module('myApp')
  .config(function($routeProvider) { $httpProvider.interceptors.push('timeoutHttpIntercept');  });

Call specific Timeout
To specifically set a custom timeout for a particular http call that you make, you can include it as part of the config object.

var app = angular.module('myApp', []);
app.controller('myCtrl',   function($scope, $http) {

// 1 minute or 60 seconds or 60,000 milliseconds
var config = {
          method : "GET",
          url : "https://www.example.com/post",
          timeout: 1 * 60 * 1000
     };

$http(config)
        .then(
           function mySuccess(response) {
            $scope.myWelcome = response.data;
           },
           function myError(response)   {
             $scope.myWelcome =   response.statusText;
         });
});

                                                         or

var app = angular.module('myApp', []);
app.controller('myCtrl',   function($scope, $http) {
    
   $http({
          method : "GET",
          url : "https://www.example.com/post",
          timeout: 1 * 60 * 1000
      })
        .then(
            function mySuccess(response) {
               $scope.myWelcome = response.data;
            },
            function myError(response)   {
               $scope.myWelcome = response.statusText;
          });
});
Categories
Uncategorized

How to redirect passport to referrer after authentication

PassortJSPassportJS by default redirects to the homepage and not the referrer, after authentication. To achieve redirection to the referrer without installing any additional plugins, all that needs to be done is to store the referrer URL in session.redirectTo variable. This can be used to later redirect the user once the authentication is performed successfully. It does not matter whether the session is stored locally or remotely (scalable applications).

Storing the referrer URL

app.use(function (req, res, next) {
    if (req.user) {
        next();
    } else {
        session.redirectTo = req.url;

       // or   session.redirectTo = req.originalUrl;
       // if that doesn't work try this
       //     require('url').parse(req.url).path;

      res.redirect('/login');
    }
});

Redirecting to required URL after successful login

// For 0Auth 2.0 Passport Strategy

app.get('/auth/provider/callback',
 passport.authenticate('provider',
  { failureRedirect: '/login' }, 
  function(req, res) {
    // You can log the user to backend API logs and then upon success        
    //redirect to referrer
   
   if (session.redirectTo)
      res.redirect(session.redirectTo);
   else 
      res.redirect('/');
 }
));
Categories
Uncategorized

How to use AngularJS Services

angularjs by googleThere are many ways in which one can use Angular Services in an Angular project. The following is a good example of a frequent use case for the angular factory. (Services can be implemented by either angular service or angular factory)

When we write a service, the main goal is to be make it modular and reusable. In the following service named ‘serviceModuleName’, we have added support for HTTP GET & POST calls. We are handling them using promises being returned. For this purpose we use the $q service in angular.

Define a Service

(function () {
    'use strict';
    angular.module('App').factory('serviceModuleName', function ($http, $q) {
        var httpDeferGet = function (url) {
            var deferred = $q.defer();
            $http.get(url)
                .then(function successCallback(response) {
                    deferred.resolve(response.data);
                }, function errorCallback(response) {
                    deferred.reject(response.status);
                });
            return deferred.promise;
        };

        var httpDeferPost = function (url, obj) {
            var deferred = $q.defer();
            $http.post(url, obj)
                .then(function successCallback(response) {
                    deferred.resolve(response.data);
                }, function errorCallback(response) {
                    deferred.reject(response.status);
                });
            return deferred.promise;
        };

   var getLaunch = function () {
    return httpDeferGet('www.example.com/test-get-endpoint');
    };

var postLaunch = function (obj) {
    return httpDeferPost('www.example.com/test-get-endpoint', obj);
};

return {
getLaunch: getLaunch,
postLaunch: postLaunch
}

});
})();

Injecting a Service into the Controller

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, serviceModuleName) {
 
});

Calling a Service from inside a Controller

Since a promise is being returned by the service we need to handle it with then, catch and finally blocks. ‘then’ returns the data, ‘catch’ catches the exception thrown and it can be handled here. Finally the ‘finally’ block of statements are executed regardless of success/failure.

$scope.callService = function(postObj) { 

 $scope.loading = true;
 
serviceModuleName.postLaunch(postObj) 
 
.then(function (data) { 
 $scope.returnedData = data; 
 }) 

 .catch(function (err) { 
 $scope.error = 'Sorry something went wrong! ' + err; 
 }) 

 .finally(function () { 
 $scope.loading = false; 
 }); 
 
};
Categories
Uncategorized

AngularJS 1.X ng-options

Using the predefined angularjs ng-options directive can be quite tricky at times. The following is a basic example of how to iterate through list of people. The value of the person that is chosen from the drop down list is store in $scope.chosenPerson and can be accessed with the same from the controller.
Example 1:


  

Output:
ng-options 1

Demo

Example 2: If you just want the value to be last name instead of the whole object  use this.


  

Output:
ng-options 1

Demo

To access a nested array and show it as part of the dropdown the following example demonstrates how to do that,

Example 3


  

Output

ng-options output2

Demo

In the above example if the countries and locations were 2 completely different objects, then a hashmap can be used to link those two objects by keys and values.