Angular UI-Router sending root url to 404

匿名 (未验证) 提交于 2019-12-03 03:06:01

问题:

I am having an infuriating issue regarding ui-router. Everything works as I want, where all bad urls are sent to the 404 state. However, even though my default state is correctly rendered when the url is /#/, the url of / is redirected to /404/. How can I server the default state to both / and /#/?

app.js

MyApp.config( function ($stateProvider, $urlRouterProvider) {  // For any unmatched url, send to 404 $urlRouterProvider.otherwise("/404/");  $stateProvider     // Home  (default)     .state('default', {         url: '/',         resolve: {             ...         },    } }); 

Any help much appreciated.

回答1:

I think this will accomplish your needs -

MyApp.config(function($stateProvider, $urlRouterProvider) {     // the known route     $urlRouterProvider.when('', '/');      // For any unmatched url, send to 404     $urlRouterProvider.otherwise('/404');      $stateProvider         // Home  (default)         .state('default', {             url: '/',             resolve: {                 // ...             }             // ....         }); }); 

I refered to this post. You may need to use a regular expression to handle routes with data.

Instead of the # in your URL you can use a query string too and grab it via $stateParams in a state.

Here is how you can do that -

  // ....    $stateProvider      .state('default', {         url: '/?data',         templateUrl: 'templates/index.html',         controller: 'defaultCtrl'     }) 

And then you can use this below to go to home with data -

var toStateData = {     key1: 'value1',     key2: 'value2' }  $state.go('default', {data: JSON.stringify(toStateData)}); 

You don't have to stringify the data in $stateParams but this will allow more options with one parameter. In the defaultCtrl controller you can get the passed query string like this -

var stateData = JSON.parse($stateParams.data); var key1 = stateData.key1; // .... 


回答2:

I wanted to do this only with states, so no url provider involved. I found the following solution which I think is good:

(sorry it's coffeescript)

  $stateProvider.     state('base.public.notFound',       url:         '^*path'       templateUrl: 'views/layouts/404.html'     ) 

Put this as the last state and you are done!



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!