Ui-router nested state and intermediate protection

According to the documentation , you can use user data and listen stateChangeto prevent access to the state based on some condition. This works without problems, but my use case is when I enter a nested state, I want all descendant state rules to be respected.

In other words, if I start with a state greenand I want to finish working in a state blue, I want the rule to loginbe evaluated. Currently, only the rule applies color. Is there any way to do this?

I understand that data is being overwritten in a child state, and the reason I see only the log is color. But what is the way to expand dataand not overwrite it?

example

here is the code:

var example = angular.module("example", ['ui.router']);

example.config(function ($stateProvider, $urlRouterProvider) {
    $stateProvider
        .state("parent", {
            url: "/parent",
            templateUrl: "templates/parent.html",
            data: {
                rule: function () {
                    console.log("login rule checked");
                    return true;
                }
            }
        })
        .state("parent.child", {
            url: "/child",
            templateUrl: "templates/child.html",
            data: {
                rule: function () {
                    console.log("color rule checked");
                    return true;
                }
            }
        });
});


example.run(function ($rootScope, $state) {
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
        if (!toState.data || !angular.isFunction(toState.data.rule)) return;
        var result = toState.data.rule();
        if (result) {
            event.preventDefault();
            $state.go(toState, result.params, {notify: false});
        } else {
            event.preventDefault();
        }
    })

});
+4
source share
1 answer

I'm not sure if this is exactly what you want, but do it:

$state.go(toState, result.params, {notify: false, reload:true});

will reload the entire state, including all parent states. This is not exactly what you want, since it can reload more than you want if state R is not the top of the tree. However, this should work in the example you are showing.

See the ui-router API for more information .

0
source

Source: https://habr.com/ru/post/1607182/


All Articles