“UI-路由器-附加' - 不能附加/添加新”FutureState“对象App.Config中()已加载后 [英] 'UI-Router-Extras' - Can't Attach / Add New 'FutureState' Objects After App.Config() Has Already Loaded

查看:577
本文介绍了“UI-路由器-附加' - 不能附加/添加新”FutureState“对象App.Config中()已加载后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有添加新的国家使用我的应用程序的运行阶段 UI-路由器-额外

I am having problems with adding new states to the runtime phase of my app using 'UI-Router-Extras'.

我一直在尝试了一段时间,现在得到新的状态连接和加载后用户已使用 UI-路由器-额外插件的 UI的路由器演员

I have been trying for quite some time now to get new states attached and loaded AFTER a user has successfully authenticated using the 'UI-Router-Extras' plugin 'ui-router-extras'

下面是对UI-路由器-附加'实例的引用为FutureState文档我使用的,但我觉得也许我的情况是要么略有不同的是什么显示或我完全失去了一些东西。

Here is a reference to the 'UI-Router-Extras' Examples for the FutureState documentation that i'm using, but I feel like maybe my scenario is either slightly different that what's shown or I'm missing something altogether.

例如:code在PLUNKER - 点击登录按钮 - > http://plnkr.co/edit/PQwNQcLNMyPfpke076yy

EXAMPLE CODE IN PLUNKER - CLICK LOGIN BUTTON -> http://plnkr.co/edit/PQwNQcLNMyPfpke076yy

结果
code以下载荷和作品:



我成功地让最初的app.config()从外部文件延迟加载。像code如下描述:


I was successful in getting the initial app.config() lazy loaded from an external file. Like the code describes below:

结果
公开 - 使用外部最初加载路由UI-路由器-附加' - 'lazyload /美国/公共states.json

[
    {
        "name": "unauth",
        "url": "/",
        "controller": "LoginCtrl",
        "templateUrl": "app/components/core/login/login.html",
        "roles": ["public"]
    },
    {
        "name": "otherwise",
        "url": "/",
        "roles": ["public"]
    }
]

初始应用负载 - 公共美国的成功延迟加载为了与开始就登录:

'use strict';

var app = angular.module('app', ['ui.router', 'ct.ui.router.extras'])

  .config(function ($urlRouterProvider, $stateProvider, $futureStateProvider) {

        app.stateProvider = $stateProvider; // MIGHT NEED REFERNCE LATER?
        app.futurestateProvider = $futureStateProvider;  // MIGHT NEED REFERNCE LATER?

        // ASYNC LOAD OF ROUTES AVAILABLE - SOON TO BE BY ROLE
        var futureStateResolve = ["$http", function($http) {
            return $http.get("lazyload/states/public-states.json").then(function(response) {
                angular.forEach(response.data, function(state) {

                    $stateProvider.state(state);
                    console.log(state.roles);

                })
            })
        }];

        $futureStateProvider.addResolve(futureStateResolve);
        console.log($futureStateProvider);

  });

搜索结果
code以下无法正常工作



下面是我的code的部分不工作:

PRIVATE - 使用外部最初加载路由UI-路由器-附加' - 'lazyload /美国/公共states.json

下面这个JSON是为了用户登录后,使用延迟加载和FutureStates添加。到目前为止,没有运气:(

This json below is meant to be added after user login using lazy loading and FutureStates. So far no luck :(

[
    {
        "name": "app",
        "abstract": true,
        "url": "?menu1State",
        "templateUrl": "app/components/core/layout/layout.html",
        "controller": "LayoutCtrl",
        "roles": ["level1"]
    },
    {
        "name": "app.dashboard",
        "url": "/app",
        "views": {
            "feature": {
                "templateUrl": "app/components/core/features/features.html",
                "controller": "FeatureCtrl"
            }
        },
        "roles": ["level1"]
    },
    {
        "name": "app.associations_beanbags",
        "url": "/app/associations/bean-bags?myParam1&myParam2&modalState",
        "views": {
            "feature": {
                "templateUrl": "app/components/core/features/associations/bean-bags.html",
                "controller": "BeanbagsCtrl"
            }
        },
        "roles": ["level2"]
    }
]

登录按钮触发认证成功后懒创建状态:

Login button triggering the lazy creation of states after successful authentication:

<a id="btn-fblogin" href="" class="btn btn-primary pull-right" ng-click="callNotify(username, password);">Login</a>

结果

会发生什么事是,当用户点击登录按钮嘲笑它的成功,并呼吁$ scope.callNotify 引发了code你看到下面。什么结束了发生的事情是一切正常,直到 app.futurestateProvider.futureState(newState); 和试图调用新的状态,看是否加入' $ state.go( app.dashboard'); 。所有这一切都在指出以下的错误结果:

What happens is when a user clicks on a login button it mocks the success and calls '$scope.callNotify' triggering the code you see below. What ends up happening is everything works up until the 'app.futurestateProvider.futureState(newState);' and the trying to call the new state to see if was added '$state.go('app.dashboard');'. All of this results in an error that states the following:

控制台错误:

Error: Could not resolve 'app.dashboard' from state 'unauth'
at Object.transitionTo (http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:2521:17)
at Object.$state.transitionTo (http://localhost:3000/bower_components/ui-router-extras/release/ct-ui-router-extras.js:136:34)
at Object.$state.transitionTo (http://localhost:3000/bower_components/ui-router-extras/release/ct-ui-router-extras.js:874:55)
at Object.$state.transitionTo (http://localhost:3000/bower_components/ui-router-extras/release/ct-ui-router-extras.js:1301:48)
at Object.go (http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:2454:21)
at http://localhost:3000/app/components/core/auth/auth-service.js:58:13
at http://localhost:3000/bower_components/angular/angular.js:8113:11
at wrappedCallback (http://localhost:3000/bower_components/angular/angular.js:11573:81)
at wrappedCallback (http://localhost:3000/bower_components/angular/angular.js:11573:81)
at http://localhost:3000/bower_components/angular/angular.js:11659:26 

那么,这看起来像对我来说,当我们的预期,从而导致一个错误说东西的喜好状态从来没有真正得到补充说:对不起,我没有看到你正在寻找的路线。

So what this looks like to me is that the states never really got added when we expected, thus causing an error saying something to the likes of "Sorry, i don't see the route you are looking for."

'use strict';

app.controller('AuthServiceTestCtrl', ['$window','$scope','$http', '$state', function (win, $scope, $http, $state) {

    $scope.callNotify = function(username,password, $stateProvider, $futureStateProvider) {
            //notify(username, password); // CALL SERVICE AND GET A RETURN VALUE / ACTION

            var loadedAgain = $http.get("lazyload/states/private-states.json").success(function(response) {

                if(username == "testuser@example.com" && password == "abc123"){

                    console.log('Valid Credentials. Logging In.');

                    // NOW THAT USER IS LOGGED IN REGISTER NEW PRIVATE ROUTE / STATES - PREFERABLY FROM THE SECURED SERVER FILE ('private-states.json') ABOVE
                    var adminModuleFutureStates = [
                        {
                            "name": "app",
                            "abstract": true,
                            "url": "?menu1State",
                            "templateUrl": "app/components/core/layout/layout.html",
                            "controller": "LayoutCtrl",
                            "roles": ["level1"]
                        },
                        {
                            "name": "app.dashboard",
                            "url": "/app",
                            "views": {
                                "feature": {
                                    "templateUrl": "app/components/core/features/features.html",
                                    "controller": "FeatureCtrl"
                                }
                            },
                            "roles": ["level1"]
                        },
                        {
                            "name": "app.associations_bean-bags",
                            "url": "/app/associations/bean-bags?myParam1&myParam2&modalState",
                            "views": {
                                "feature": {
                                    "templateUrl": "app/components/core/features/associations/bean-bags.html",
                                    "controller": "BeanBagsCtrl"
                                }
                            },
                            "roles": ["level2"]
                        }
                    ];

                    angular.forEach(adminModuleFutureStates, function(newState) {
                        console.log(newState);
                        app.futurestateProvider.futureState(newState); // WAS SAVED AS A VAR IN APP CONFIG FOR LATER REFERENCE
                    });

                    // FINALLY GO TO ONE OF THE NEWLY ADDED PRIVATE STATES WE JUST ADDED WHICH IS A DASHBOARD
                    $state.go('app.dashboard');

                }
            });

        };
    }]);

我很抱歉没有工作示例准备好了,我在它的权利,但我想我会张贴此我们展示什么,我已经和可能得到讨论或解决方案,如何我可以通过我以上后,应用程序已经加载上市的控制器在运行时加载州UI路由器的配置等。

I'm very sorry for not having a working example ready, I'm on it right now, but i figured i'd post this now to show what I do have and possibly get a discussion or solution as to how I can load states to ui-router at runtime via my controller listed above after the application has already loaded the config etc..

我试图最终在这里做的是这样的:

What I'm trying to ultimately do here is this:

我真的只需要公开两个安全的公共路线与开始上登录。然后,一旦在$ p $用户登录pvious公众留下航线,我尝试添加或装饰用新的,现在允许用户只能访问自己的角色提供路由现有的路线。安全性对我们来说是非常重要的,我没有看到任何好处任何加载每一个可能的路径前期的登录页面上让别人知道是什么了API或服务器击溃是没有,至少被记录在

I really need to only expose two safe public routes to begin with on login. Then once a user logs in the previous public routes stay and i'm trying to add or decorate the existing routes with new ones that now allow the user to only have access to the routes their role provides. Security for us is extremely important and I do not see any benefit whatsoever loading every possible route upfront on a login page letting someone know what out api or server routs are without at least being logged in.

我为散漫很抱歉,我是来给我只是平这样做是错误的,需要一些额外的眼睛这样的结论也许赶上为什么我不能添加新的状态后负荷。

I'm very sorry for rambling but I've come to the conclusion that I'm just flat doing it wrong and need some extra eyes to maybe catch why i can't add new states post load.

说真的太感谢你了!

例如:code在PLUNKER - 点击登录按钮 - > http://plnkr.co/edit/PQwNQcLNMyPfpke076yy

EXAMPLE CODE IN PLUNKER - CLICK LOGIN BUTTON -> http://plnkr.co/edit/PQwNQcLNMyPfpke076yy

推荐答案

我决定用$ ocLazyLoad服务,而不是,但仍然使用一个应用程序喷油器动态地添加路由的应用程序加载,并已初步与基本配置后,认证前的公共线路等。

angular.module("app").configInjector.invoke(['$stateProvider', function ($stateProvider) {

再经过喷油器的应用程序是设置和用户通过身份验证和角色(S)是由服务器验证的JSON响应定义允许的UI路由器意见/路由/状态循环结束,动态添加到用户界面 - 路由器的状态定义。这些路线在JSON定义,但这样是任何附带的控制器和视图延迟加载使用$ ocLazyLoad。

Then after the app injector was setup and the user was authenticated and a role(s) was validated by the server a json response defining the allowed ui-router views / routes / states are looped over and added dynamically to the ui-router state definitions. These routes are defined in the json but so is any accompanying controllers and views that are lazy loaded using $ocLazyLoad.

总之我最终做了以下内容:

angular.module("auth")
.factory('AuthRouteLoaderFactory', ['$window', '$rootScope', '$http', '$state', '$cookieStore','$location', '$timeout','AuthSession',
    function(win, $rootScope, $http, $state, $cookieStore, $location, $timeout, AuthSession) {

        // PRIVATE INTERFACE
        function loadPrivateRoutes() {

            console.log('AuthRouteLoaderFactory :: LOADING PRIVATE ROUTES');

            var loadedPrivateRoutes = $http.get("lazyload/states/private-states.json").success(function (response) {

        angular.module("app").configInjector.invoke(['$stateProvider', function ($stateProvider) {

                    // VERY IMPORTANT - POST LOGIN ROUTE LOADER / INJECTOR;// DYNAMIC AND SERVER DETERMINED JSON ITERATED BASED ON SPECIFIC ROLES PRE-MADE BY SERVER.
                    angular.forEach(response, function (state) {

                        if(!state.abstract){
                            state.views.feature.resolve[state.views.feature.data.controllerAlias] = ['$ocLazyLoad', function($ocLazyLoad){return $ocLazyLoad.load({"name": state.views.feature.data.controllerAlias,"files": state.views.feature.data.controllerFiles})}];
                            state.views.feature.resolve.isAuthenticated = function(){
                // CHECK IF WE ARE A VALID SESSION FOR EACH LAZY LOAD
                //AuthSession.validateToken();
              };
                        }

                        console.log('AuthRouteLoaderFactory :: loadPrivateroutes state loaded -> ' + state.name);
                        $stateProvider.state(state.name, state);
                    });

                    $state.go('app.dashboard');

                }]);

            });

        }

        // FOR NOW WE LOAD ROUTES ANYWAY UNTIL WE CALL API'S /ME OR PING SERVICE, THEN ON SUCCESS WE LOAD ROUTES
        if(AuthSession.validateToken()){
          $rootScope.hideLoader = true;
          loadPrivateRoutes();
          console.log('AuthRouteLoaderFactory :: SESSION VALIDATION SUCCESSFUL :: PROCEED');
        }

        // PUBLIC INTERFACE
        return {
            testFactory: function() {
                console.log('AuthRouteLoaderFactory :: testFactory');
            },
            isSessionValid: function(){
                return $cookieStore.get('fakeLoginSession');
            },
            invalidateSession: function(){
                $cookieStore.remove('fakeLoginSession');
                $location.path('/login.html');
            },
            loadRoutes: loadPrivateRoutes
        };
    }
]);

公开美国/路线:

[
    {
        "name": "unauth",
        "url": "/",
        "controller": "LoginCtrl",
        "templateUrl": "app/components/core/login/unauth.html",
        "data": {
            "roles": ["public"]
        }
    },
    {
        "name": "login",
        "url": "/login",
        "controller": "LoginCtrl",
        "templateUrl": "app/components/core/login/unauth.html",
        "data": {
            "roles": ["public"]
        }
    },
    {
        "name": "otherwise",
        "url": "/",
        "data": {
            "roles": ["public"]
        }
    }
]

私人美国/路线:

[
    { "name": "app", "abstract": true, "url": "", "templateUrl": "app/components/core/layout/layout.html", "controller": "LayoutCtrl" },
    {
        "name": "app.dashboard",
        "views": {
            "feature": {
                "templateUrl": "lazyload/components/core/features/dashboard/dashboard.html",
                "controller": "DashboardCtrl as dashboard",
                "resolve": {},
                "data": {
                    "controllerAlias": "dashboard",
                    "controllerFiles": ["lazyload/components/core/features/dashboard/dashboard-controller.js"]
                }
            }
        }
    },
    {
        "name": "app.associations_role-type",
        "views": {
            "feature": {
                "templateUrl": "lazyload/components/core/features/associations/role-type.html",
                "controller": "RoleTypeCtrl as roleType",
                "resolve": {},
                "data": {
                    "controllerAlias": "roleType",
                    "controllerFiles": ["lazyload/components/core/features/associations/role-type-controller.js"]
                }
            }
        }
    }
]

这篇关于“UI-路由器-附加' - 不能附加/添加新”FutureState“对象App.Config中()已加载后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆