我想在我的 Angular 应用程序中设置一些重定向。
现在我有:
$urlRouterProvider.otherwise('/notfound');
因此,如果路径与任何定义的状态不匹配,它将进入“未找到”状态。
但是,我想修改此行为,以便当路径与任何定义的状态不匹配时,首先针对重定向数组进行 Angular 检查。如果没有匹配,它将转到“未找到”。如果存在匹配,Angular 将硬重定向到匹配的 URL。
伪代码:
var redirects = [{'/a_certain_path':'http://www.someaddress.com/'}];
if(URL != defined state){ // path doesnt match any state
if( URL in redirects araay ){ // path matches value in array
window.location = redirects[URL]; // redirect to match
} else $state.go('base.notfound');
} else {
$state.go('base.notfound');
}
我尝试了一些方法(例如在“未找到”状态下使用解析),但显然这不起作用,因为当我到达那里时路径已经是“/notfound”。
最佳答案
var redirects = [{name:'/a_certain_path',url:'http://www.someaddress.com/'}];
$urlRouterProvider.otherwise(function ($injector) {
var $state = $injector.get('$state');
if(redirects){
var firstRedirect=redirects[0];
redirects.splice(0,1);//if there is more than one
redirects not check invalid
again
if($state.href(firstRedirect.name))
{
$state.go(firstRedirect.name)
}
else
{
window.location =firstRedirect.url;
}
}
else{
$state.go('base.notfound');
}
});
关于javascript - 使用 ui-router/Angular JS 设置重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45947317/