Angular: $http 404 error handling

前端 未结 2 1794
醉酒成梦
醉酒成梦 2020-12-09 12:15

i have an HTML with 2 ng-includes. Consider if one of the ng-include src is not present in the server. as of now it would just load blank html and in the browser console it

相关标签:
2条回答
  • 2020-12-09 12:40

    To handle this kind of situations you could use http interceptors (find the docs here: $http).

    Interceptor has to catch the 404 response, load the 404.html page from your server and set it as a data for the initial response along with the status code 200.

    I've created a project that shows how to solve it.

    Repository: https://github.com/matys84pl/angularjs-nginclude-handling-404/

    Take a closer look at the main.js file.

    0 讨论(0)
  • 2020-12-09 12:43

    I did something similar by passing the desired ng-include url through $http directly before populating the ng-include value.

    $http({ url: url, method: "GET", cache: $templateCache}).success(function(data) {
            /* there was a template for this url - set the $scope property that 
             * the ng-include is using
             */
            $scope.templateUrl = url;
        }).error(function () {
            // there was not a template for this url - set the default one
            $scope.templateUrl = defaultUrl;
        });
    

    The trick here is passing $templateCache in as the cache argument to $http - this means that the fetched url is stored in the same cache that ng-include uses, and so when you find a valid template and set it in the templateUrl property, ng-include does not need to fetch the template again.

    0 讨论(0)
提交回复
热议问题