Display "not found" page/redirect when routing to an item that doesn't exist

1,144 views
Skip to first unread message

Ben Foster

unread,
Jan 31, 2014, 10:39:18 AM1/31/14
to ang...@googlegroups.com
I've just completed the Phone Catalog tutorial on the Angular site.

In most data driven applications if a user navigates to an item that does not exist e.g. /phones/some-id we would return a 404 page.

How is this handled in an Angular app? In the tutorial if you navigate to a phone that does not exist (e.g. index.html#/phones/foo) it just breaks. Ideally we would redirect to a "not found" view or display some kind of notification to the user.

Thanks,

Ben
Message has been deleted

Alon Nisser

unread,
Feb 1, 2014, 4:53:02 PM2/1/14
to ang...@googlegroups.com
Hey ben, it depends.. You can handle this in a number of ways, but basically all boiles to this:

1. If the url was valid (using ng-router, ui-router, or whatever ) and the data comes from the server - check for the error response. if it was 404 then redirect to the 404 url with  the related view, etc.

for example in UI router I would try to resolve the data in the ```state``` ```resolves```. and then listen to a $StateChangeError event, if the state failed to resolve the data from the server it would emit a stateChangeError. now I can grap the error args. something like this (psuedo code.. not syntax checked):
<pre>
  $rootScope.$on('$stateChangeError',
     function(event, toState, toParams, fromState, fromParams, error){
       if (error.status === 404) {
        $location.path('/404/')
      }
... }) 
</pre>
2. If the url wan't valid (not an existing url in your config) just redirect to the 404 view. both ng-router and ui-router have a "othewise" option allowing you do to catch all url's that do not have an explicit definition in the config.
Reply all
Reply to author
Forward
0 new messages