有条件的“;否则“;Angular中的布线

Conditional "otherwise" routing in Angular

本文关键字:布线 否则 有条件 Angular      更新时间:2023-09-26

我熟悉angular中的"$urlRouterProvider.otherwise('{route here}')"语法,可以在angular UI Router中用作catch-all。

我想知道的是,当路由输入错误时,有没有一种方法可以根据父状态进行有条件的"其他"路由?

例如,假设我有以下配置:

$stateProvider
.state('core', {configuration here})
.state('core.page1', {configuration here...})
.state('dashboard', {configuration here})
.state('dashboard.page1', {configuration here})
$urlRouterProvider.otherwise('/core/page1');

我希望在任何时候输入具有"/core/{route here}"的路线,
如果它与任何当前状态都不匹配,则路由回'/core/page1'
并且只要输入了具有与任何当前状态都不匹配的"/dashboard/{route here}"的路由,就可以路由回"/dashboard/page1"

有人有做这件事的经验,或者知道我该怎么做?Angular中是否内置了允许这种行为的内容?

提前感谢!

如所示

使用ui路由器显示404错误页面时如何不更改url

.otherwise()不必是字符串(url)。。。它可能是一个聪明的决策者:

$urlRouterProvider.otherwise(function($injector, $location){
   var state = $injector.get('$state');
   if(....)
     state.go('core');
   else(...)
     state.go('dashboard');
   ...
   return $location.path();
});

文件:

$urlRouterProvider.否则(规则)

定义在请求无效路由时使用的路径。

string-要重定向到的url路径或返回url路径的函数规则
函数版本传递了两个参数:$injector和$location服务,并且必须返回一个url字符串。