Fred Collins
Fred Collins

Reputation: 5010

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:

enter image description here

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

Upvotes: 0

Views: 494

Answers (1)

Per Johansson
Per Johansson

Reputation: 43

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)

Upvotes: 2

Related Questions