简体   繁体   中英

Handling 404 in resolve with angular-ui-router

I have a service with a method:

service.getVenueBySlug = function(slug) {
    return $http.get(API + '/venue/' + slug);
};

In my app.routes.js`:

.state('app.venue', {
  url: '/venues/:venueSlug',
  templateUrl: '/app/views/venue.html',
  controller: 'VenueController',
  resolve: {
    venue: ['VenueService', '$stateParams', '$state', function (VenueService, $stateParams, $state) {
      return VenueService.getVenueBySlug($stateParams.venueSlug).then(function(res) {
        return res.data;
      }).catch(function(err) {
        $state.go('app.404');
      });
    }]
  }
})

The controller VenueController simply has:

$scope.venue = venue

Everything is working and it's correctly redirecting to 404 if I manually go to an URL with a wrong venue slug.

The issue is that I'm receiving an error in the console that it's bothering me:

在此处输入图片说明

Does anyone know how to fix? I'm using angular 1.6.4 and angular-ui-router 1.0.6.

As mentioned in a comment to your post - in your resolve's catch, you probably should do something in the lines of: return $q.reject({redirectTo: app.404});

Then in your router config you listen to stateChangeErrors:

$rootScope.$on('$stateChangeError',
   function(event, toState, toParams, fromState, fromParams, error) {
      if(error.redirectTo) {
         $state.go(error.redirectTo);
      }
   } 
})

the $q.reject is required to handle (interrupt) the current stateChange, and the stateChangeError is there to handle that reject.

(haven't tested the code but I remember having a similar solution in one of my projects)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM