S
S
SerzN12016-06-06 18:15:50
Angular
SerzN1, 2016-06-06 18:15:50

How to organize data loading with authorization check in Angular?

There was such a question. When entering the route, a certain controller is triggered and loads the data.
The code:

angular.module('app.Images', [])

  .controller('ImagesCtrl', function($scope, $http, $window, imagesUrl) {
    var _this = this;

    $scope.images = {};

    $http.get(imagesUrl)
      .success(checkResponse);

    function checkResponse (data) {
      if (data.success && data.data) {
        $scope.images = data.data;
      } else if (data.error) {
        alert(data.error);
      } else if (data.reload) {
        $window.location.reload(true);
      }
    }

On each route, you have to check data.reload.
What is the best way to do data loading and similar checks on all entry points?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
SerzN1, 2016-06-07
@SerzN1

You can add a $http response interceptor, globally or for specific requests.
Sample global interceptor response:

$httpProvider.interceptors.push(function($window) {
  return {
    response: function(response) {
       if(response.data && response.data.reload) {
            $window.location.reload(true);
       }
    }
  };
});

And a big thanks to stackoverflow, and a big button accordion to "our" wonderful answers - like googling dude!

S
Sergey, 2016-06-06
Protko @Fesor

in uiRouter and ngRoute, this is handled by resolvers.
ps 2016, angular 1.5, and you not only use scope, but also controllers.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question