How do you pass more meaningful error information

2020-03-30 09:07发布

I have incredibly meaningful and powerful error messages that my server passes to the browser if there was any kind of error. But how do I access that info in the following:

$rootScope.$on("$routeChangeError", function (event, current, previous, rejection) {
    console.log(rejection); // "An unknown error has occurred."
});

I'm using $routeProvides.resolve in my route definitions, and so $routeChangeError was going to be my way of handling if those promises didn't resolve. Is there for a way for me to access the response from the server and display that somehow?

Thanks!

标签: angularjs
2条回答
▲ chillily
2楼-- · 2020-03-30 09:40

You dont need to do this in this way, you can do this in your Controller:

In some service:

angular.module('app').service('SomeService', function($http) {

 this.getData = function() {

   return $http.get('url');

 }

})
.controller('MainCtrl', function(SomeService) {

  SomeService.getData().then(function(response) {

   //the promise is resolved
   // response is the response from server

}).catch(function(error) {

  console.log(error) // this error is from your server if the promise rejected
  // Then you can add {{error}} on your html and add here
  $scope.error = error.data;

});

});
查看更多
叼着烟拽天下
3楼-- · 2020-03-30 09:44

Each property on a resolve object should be a function that returns a promise. So if one of your routes doesn't resolve, throwing a reason in the .catch handler will pass your error information to the $routeChangeError handler

$routeProvider
  .when("/foo", {
     templateUrl: "foo.html",
     controller: "fooController",
     resolve: {
         message: function($http){
             return $http.get('/someUrl').
             then(function(response) {
               return response.data;
             }).
             catch(function(response) { 
               throw response.data;
             });
     }
  }
});

Assuming the data parameter has the data from the server you want to use, this will end up in the rejection parameter on the $routeChangeError event.

查看更多
登录 后发表回答