How to avoid $compile:tpload errors on 401 status code response

こ雲淡風輕ζ 提交于 2019-12-02 20:47:41

After some thinking I remembered about decorating in Angular, it solved this problem perfectly:

app.config(['$provide', function($provide) {
  $provide.decorator('$templateRequest', ['$delegate', function($delegate) {

    var fn = $delegate;

    $delegate = function(tpl) {

      for (var key in fn) {
        $delegate[key] = fn[key];
      }

      return fn.apply(this, [tpl, true]);
    };

    return $delegate;
  }]);
}]);

You should be able to intercept the call for the template by status and url.

Plunker

app.config(function($httpProvider) {

  var interceptor = function($location, $log, $q) {

      function success(response) {
        // The response if complete
        $log.info(response);
        return response;
      }

      function error(response) {
        // The request if errors
        $log.error(response);
        return $q.reject(response);
      }

      return function(promise) {
        return promise.then(success, error);
      }
    }

  $httpProvider.responseInterceptors.push(interceptor);

});

As I see it, you have two options:

Option A)

go with the interceptors. However, to eliminate the compile you need to return success status code inside response error (BAD) OR redirect to the login page inside the interceptor (Good):

app.factory('authInterceptorService', function () {

    var interceptor = {};

    interceptor.responseError = function (rejection) {

        if (rejection.status === 401 && rejection.config.url === "home template url") {

            //BAD IDEA
            //console.log("faking home template");
            //rejection.status = 200;
            //rejection.data = "<h1>should log in to the application first</h1>";

            //GOOD IDEA
            window.location = "/login.html";
        }

        return rejection;
    }


    return interceptor;
});

and on app config:

app.config(['$httpProvider', function ($httpProvider) {

   $httpProvider.interceptors.push('authInterceptorService');
}

Option b)

make the home template public. After all it should be just html mark-up, without any sensible information.

this solution is clean...and perhaps is also possible.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!