ocombe / ocLazyLoad

Lazy load modules & components in AngularJS
https://oclazyload.readme.io
MIT License
2.63k stars 510 forks source link

Use ocLazyLoad with a router and an interceptor #255

Closed sieira closed 8 years ago

sieira commented 8 years ago

It's kind of a long question, you can see it in detail here:

http://stackoverflow.com/questions/33098172/how-to-make-an-interceptor-request-a-route-that-run-a-lazy-loaded-angular-modu

I'm trying to use the lazy loader to open a modal login whenever an interceptor catches an unauthorized response.

So, I ended up doing it without the router, and bypassing a function between a controller and a factory, which is just... pas terrible.

You can see how it's done here (as well as in the stackoverflow question).

You can see the way I was expecting to do it in the second part of the stackoverflow question.

Using the stateProvider I managed to do it, but again I had to bypass the $state.go from the controller, since $state provokes a circular reference with $http in the factory.

This comes probably from my missunderstanding about angular, and may not be an ocLazyLoad issue, but I couldn't think of a better place to ask.

Dans l'attente de votre réponse, machin bidule truc, mes salutations déglinguées etc.

sieira commented 8 years ago

Nevermind, I ended up breadcasting and catching on the main app like so:

.run(function($rootScope, $ocLazyLoad) {
  var popLogin = $rootScope.popLogin = function () {
    return $ocLazyLoad.load({
      cache: false,
      rerun: true,
      files: ['modules/auth/js/app.js']
    });
  };

  $rootScope.$on('unauthorized', function() {
    popLogin();
  });
})
.factory('authInterceptor', function($rootScope, $q, $log) {
  return {
    response: function(response) {
      if (response.status === 401) {
        $log.debug("Response 401");
        $rootScope.$broadcast('unauthorized');
      }
      return response || $q.when(response);
    },
    responseError: function(rejection) {
      if (rejection.status === 401) {
        $log.debug("Response Error 401",rejection);
        $rootScope.$broadcast('unauthorized');
      }
      return $q.reject(rejection);
    }
  };
})