0

I would like to setup some redirects in my angular app.

Right now I have:

$urlRouterProvider.otherwise('/notfound');

So if path doesnt match any of the defined states, it will go to the "not found" state.

However, I would like to modify this behavior such that when a path doesnt match any of the defined states, angular checks against an array of redirects first. If none match, it will go to "not found". If there is a match, angular will do a hard redirect to the matching URL.

In pseudo code:

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

Ive tried a few thing (like using resolve in my 'not found' state) but obviously this doesnt work because the path is already "/notfound" by the time I get there.

yevg
  • 1,846
  • 9
  • 34
  • 70
  • Possible duplicate of [How would I have ui-router go to an external link?](https://stackoverflow.com/a/30221248/2435473) – Pankaj Parkar Aug 29 '17 at 20:08
  • not a duplicate as this is includes specific logic needed for matching urls to redirects – yevg Aug 29 '17 at 20:15

1 Answers1

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

            }

        });
Ramin Farajpour
  • 297
  • 2
  • 10