AngularJS When and Otherwise with UI Rout

寵の児 提交于 2019-12-25 07:48:07

问题


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


    });    
});


来源:https://stackoverflow.com/questions/40864366/angularjs-when-and-otherwise-with-ui-rout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!