我有以下 Angular 函数。
功能:
var App = angular.module('app', ['ui.bootstrap', 'ngRoute', 'ngAnimate']); App.config(['$routeProvider', function($routeProvider) { $routeProvider .when('/', { templateUrl: 'views/dashboard.html' }) .when('/:pages', { templateUrl: function(routeParams) { return 'views/' + routeParams.pages + '.html'; } }) .otherwise({redirectTo: '404.html'}) }]);
我有一个侧边栏导航控件。我已经创建了 4 个页面。
因此,当我单击这些导航项时,相应的页面会正确打开。
还有一些页面我还没有创建。但按照下面的函数。
当我没有不存在的东西时,它必须返回到文件夹根目录中存在的404.html
文件。
发生的情况是,我在控制台中没有收到错误,并且地址栏中的 URL 反射(reflect)了上次单击的有效页面。
有人让我知道我在哪里犯了错误以及这种方法对于动态路由是否正确?
最佳答案
otherwise()
部分捕获与任何指定路由都不匹配的路径。
在您的情况下,路由匹配,但模板在指定的 URL 处不可用。
$routeProvider
对此一无所知,也无能为力。
您可以做的是以某种方式(见下文)检查模板是否可用,如果不可用,则使用$location
重定向到适当的路径(例如/error/404
)。
为了确定页面是否有效(即其模板可用),您可以尝试访问模板(使用 $http
)并捕获任何错误(表明没有模板)等但我不喜欢这种方法(因为在我看来,依赖模板的可用性来确定页面的存在/有效性并不是一个很好的做法 - 例如,在网络或网络情况下,它很容易导致误导性的错误消息)服务器问题等)。
我最喜欢的方法是保留“有效”/现有页面的列表并对其进行检查。如果当前页面可用,则照常继续获取模板等。如果不可用,则重定向到错误页面。
上述逻辑可以放置在 $routeProvider
的 resolve
属性中(因此它会在实例化 Controller 和加载 View 之前执行)。
例如:
var app = angular.module(...);
// This should be a constant, so it can
// get injected into configuration blocks
app.constant('EXISTING_PAGES', [
'page1',
'page2',
...
]);
app.config(function configRouteProvider($routeProvider, EXISTING_PAGES) {
$routeProvider.
when('/', {
templateUrl: 'views/dashboard.html'
}).
when('/:page', {
templateUrl: function getPageTemplateUrl(routeParams) {
return 'views/' + routeParams.page + '.html';
},
resolve: {
exists: function resolveExists($location, $route) {
// Because this is executed before the instantiation of the
// controller and the view is not fully loaded yet, the parameters
// should be accessed via `$route.current.params`
if (EXISTING_PAGES.indexOf($route.current.params.page) === -1) {
// This is not a valid/existing page,
// let's redirect to an appropriate error page
$location.replace(); // Replace the URL in the history
$location.path('/error/404');
}
return true;
}
}
}).
// This should be a separate route, so we can redirect to it
when('/error/404', {
templateUrl: '404.html'
}).
otherwise({
redirectTo: '/error/404'
});
});
<小时/>
另请参阅此 short demo 。
关于javascript - 页面不会重定向到无效网址上的指定页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24862225/