How to catch the wrong URL?

I am creating a simple HTML website using Angular JS ui-router.

I created a custom 404 page ("www.mysite / # / error / 404"), which the user is redirected to if the user enters a URL, for example, "www.mysite / # / invalidUrl". This functionality was achieved using the following code snippet:

$urlRouterProvider .when('', '/') .when('/home', '/') .otherwise('/error/404'); 

And the following snippet of state:

 $stateProvider.state('404', { parent: 'app', url: '^/error/404', views: { ' errorContent@main ': { controller: 'error404Controller', templateUrl: 'js/general/templates/error404.html' } } }); 

I am trying to capture the wrong URL requested by the user to display to the user as shown below.

The URL you requested was not found.
Request: www.mysite.com/#/invalidUrl

I tried to listen for the $ stateNotFound event, which seems to fire only when a certain invalid state is requested. I also tried to listen for the events of "$ StateChangeStart", "$ locationChangeStart" and "$ locationChangeSuccess", but could not find a way to achieve this functionality.

Is it possible? Please share your thoughts - thanks

+6
source share
1 answer

Awesome! Thanks to Radim Köhler . I don’t know how I didn’t land on this thread when I searched, but it helped me get an answer.

I modified the answer in this thread to fit my scenario, which I am going to leave below for links to other users.

 $stateProvider.state('404', { parent: 'app', url: '^/error/404', views: { ' errorContent@main ': { controller: 'error404Controller', templateUrl: 'js/general/templates/error404.html' } } }); $urlRouterProvider .when('', '/') .when('/home', '/') .otherwise(function ($injector, $location) { var state = $injector.get('$state'); state.go('404', { url: $location.path() }, { location: true }); }); 

So, the magic change was a function defined for the “otherwise” option. I have not changed the status URL to "error". Instead, I used "state.go" to activate the "404" state and passed the location path as a state parameter.

Setting location=true will lead you to the status url, and location=false will not. Whichever way you choose the wrong URL, you can now easily access it.

+6
source

All Articles