Handling $ routeChangeError with .catch ()

I am doing basic routing with ngRoute. I define a service that uses $httpand connects it to resolve. I usually use it explicitly $qin the service, but this time I use the built-in .thenand .catch, and it does not work, as usual. Here is the version of what I have guessed:

app.config(["$routeProvider", "$locationProvider", 
    function($routeProvider, $locationProvider){
        $locationProvider.html5Mode(false);

        $routeProvider
            .when("/", {
                templateUrl: "views/index.html",
                controller: "indexCtrl",
                resolve: {
                    myData: function(myService){
                        return myService.getMyData();
                    }
                }
            })

            .otherwise({
                templateUrl: "views/404.html"
            });
    }]);

Service:

app.factory("myService", ["$http", "$route", function($http, $route){
    return {
        getMyData: function(){
            return $http.get("www.url.com")
                .then(function(data){
                    return data;
                })
                .catch(function(err){
                    return {err: "There was an error"};
                })
        }
    }
}]);

And the controller where the error is processed:

app.controller("errorCtrl", ["$rootScope", function($rootScope){

    $rootScope.$on("$routeChangeError", function(event, current, previous, rejection){
        console.log("err", rejection);
    })

}]);

And in the view:

<body ng-app="App" ng-controller="errorCtrl" ng-view>

, , catch(), rejection routeChangeError. deferred.reject(data), , .catch() . , .catch, , . - , routeChangeError , catch. , - , ?

+4
1

return catch, , . . Chained promises, .

throw ( ), :

getMyData: function(){
    return $http.get("www.url.com")
    .catch(function(err){
        throw new Error("There was an error");
    })
}

( .then(identity))

+3

Source: https://habr.com/ru/post/1620572/


All Articles