AngularJS When and Otherwise with UI Rout

2019-09-19 06:15发布

问题:

I'm new angular student. I have a problem with my routes of UI Route.

here is my code:

  $urlRouterProvider
    .when('/GRN', '/GRN/Produtos')
    .when('/Executivo', "Executivo/Produtos")
    .otherwise("/NotFound")

i want to do this:

When -> /GRN/SOME_WRONG_LINK -> go to /GRN/Produtos
When -> /Executivo/SOME_WRONG_LINK -> go to /Executivo/Produtos
When -> /SOME_WRONG_LINK -> Go to NotFound

Basically i want if the user start putting right URL (in this case GRN or Executivo), he goes to one main page of this link, and no to "NotFound", because he starts with a right link.

Can anyone help me please?

Thanks a lot!!

回答1:

Using $routeProvider:

Since you used $routeProvider in your question,

you can use,

.c.run(function($rootScope,$location,$state) {

$rootScope.$on( '$stateChangeStart', function(e,toState,toParams,fromState,fromParams) {

    if( $location.path().search('GRN') > -1)
    {
        $state.go('GRN_Produtos');
        event.preventDefault();     
    }

    if( $location.path().search('Executivo') > -1)
        $state.go('Executivo_Produtos');
        event.preventDefault();     
    }

    $urlRouterProvider.otherwise("/");

});    

});onfig(['$routeProvider', function($routeProvider) { $routeProvider

  .when('/GRN',{redirectTo:'/GRN/Produtos'})  

  .when('/Executivo',{redirectTo:'/Executivo/Produtos'})  

  .otherwise({redirectTo: '/NotFound'}); 
}])

redirectTo:

{(string|Function)} => value to update $location path with and trigger route redirection.

Here is the reference od redirectTo

Using $stateProvider:

Assuming your states as below,

.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
    $stateProvider
        .state('GRN_Produtos', {
            url: '/GRN/Produtos',
            templateUrl: '',
            controller: ''
        })
        .state('Executivo_Produtos', {
            url: '/Executivo/Produtos',
            templateUrl: '',
            controller: ''
        })
      .state('otherwise', {
            url: '/notfound',
       });

    }])

Now you can redirect in the run block,

  .run(function($rootScope,$location,$state) {

    $rootScope.$on( '$stateChangeStart', function(e,toState,toParams,fromState,fromParams) {

        if( $location.path().search('GRN') > -1)
        {
            $state.go('GRN_Produtos');
            event.preventDefault();     
        }

        else if( $location.path().search('Executivo') > -1)
            $state.go('Executivo_Produtos');
            event.preventDefault();     
        }
        else
        {
            $state.go('otherwise');
            event.preventDefault();     
        }


    });    
});