2017-08-29 28 views
0

我想在我的角度应用中设置一些重定向。用ui-router/Angular JS设置重定向

现在我有:

$urlRouterProvider.otherwise('/notfound'); 

所以,如果路径犯规匹配任何定义的状态,就会进入“未找到”状态。

但是,我想修改此行为,以便当路径不符合任何定义的状态时,首先对重定向数组进行角度检查。如果没有匹配,它将转到“未找到”。如果存在匹配,则角度会对匹配的网址进行硬重定向。

在伪代码:

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”的时候我到达那里。

+0

的可能的复制[我怎么会对UI路由器到一个外部链接?](https://stackoverflow.com/a/30221248/2435473) –

+0

不是重复的,因为这是包括所需的特定逻辑用于将网址与重定向进行匹配 – yevg

回答

1
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'); 

      } 

     });