使用 ui-router/Angular JS 设置重定向

Set up redirect with ui-router/Angular JS

我想在我的 angular 应用程序中设置一些重定向。

现在我有:

$urlRouterProvider.otherwise('/notfound');

因此,如果路径不匹配任何定义的状态,它将进入 "not found" 状态。

但是,我想修改此行为,以便当路径不匹配任何定义的状态时,angular 首先检查重定向数组。如果 none 匹配,它将转到 "not found"。如果有匹配,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');
}

我尝试了一些方法(比如在我的 'not found' 状态下使用 resolve)但显然这不起作用,因为当我到达那里时路径已经“/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');

            }

        });