Angular UI-Router 将根 url 发送到 404 [英] Angular UI-Router sending root url to 404
问题描述
我有一个关于 ui-router
的恼人问题.一切都如我所愿,所有错误的 URL 都被发送到 404
状态.但是,即使我的默认状态在 url 为 /#/
时正确呈现,/
的 url 被重定向到 /404/
.如何将 default
状态同时提供给 /
和 /#/
?
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: {
...
},
}
});
推荐答案
我认为这将满足您的需求 -
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.
您也可以使用查询字符串代替 URL 中的 #
,并通过 $stateParams
在状态中获取它.
Instead of the #
in your URL you can use a query string too and grab it via $stateParams
in a state.
你可以这样做 -
// ....
$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)});
您不必将 $stateParams
中的数据字符串化,但这将允许一个参数有更多选项.在 defaultCtrl
控制器中,您可以像这样获取传递的查询字符串 -
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;
// ....
这篇关于Angular UI-Router 将根 url 发送到 404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!