Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct method to Redirect from $http.post in angularjs

Can you tell me what is the correct way to redirect to another page if $http.post returns a specific error code.

Just to add context, I want to redirect to another page if the user is not logged in or authorized to use the API.

  function getData(filter) {
     var deferred = $q.defer();
     var data = JSON.stringify(filter);

      $http.post('/myapp/api/getData', data)
         .success(function (data, status, headers, config) {
            deferred.resolve(data);
         })
              .error(function (error) {
                 deferred.reject(error);
              });

     return deferred.promise;
  }
like image 278
Robben_Ford_Fan_boy Avatar asked Oct 21 '16 21:10

Robben_Ford_Fan_boy


1 Answers

You could do a redirect to the page using $window.location.href, based on the error condition you have.

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

app.controller("sampleController", [
  "$scope",
  '$window',
  'sampleService',
  function($scope, $window, sampleService) {
    sampleService.getData().then(function(result) {}, function(error) {
      if (error.statusCode === 400) {
        alert("Error");
        $window.location.href = "http://stackoverflow.com"
      }
    });
  }
]);
app.service("sampleService", function() {
  this.getData = function() {
    var promise = new Promise(function(resolve, reject) {
      setTimeout(function() {
        reject({
          statusCode: 400
        });
      }, 1000);
    });
    return promise;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-App="sampleApp">
  <div ng-controller="sampleController">
  </div>
</div>
like image 147
Sreekanth Avatar answered Sep 28 '22 04:09

Sreekanth