Verifying route preconditions prior to loading controller

前端 未结 4 688
广开言路
广开言路 2021-02-15 17:27

I\'m writing a single page application in Angular, specifically angular.dart, but I\'m assuming this question still applies to AngularJS.

Take for example the followin

4条回答
  •  迷失自我
    2021-02-15 18:16

    Angular.Dart and Angular.JS routing frameworks are very/fundamentally different. Angular.Dart is using a third party routing framework (https://github.com/dart-lang/route/tree/experimental_hierarchical) and only implements angular specific features like ng-view and ways to bind routes to templates via ViewFactory.

    So your question really falls into the route_hierarchical package domain. Currently you can veto users attempt to navigate away from a route, but I guess what you want the ability to veto user entering a route depending on if the user is logged in or not. Unfortunately this is not yet supported, but is planned.

    What you could try in the meantime is creating a custom viewFactory wrapper.

    class RecipesRouteInitializer implements RouteInitializer {
       void init(Router router, ViewFactory view) {
         router
           ..addRoute(
              name: 'login',
              path: '/login',
              enter: authView(router, view('login.html'), NOT_AUTH))
           ..addRoute(
              name: 'register',
              path: '/register',
              enter: authView(router, view('register.html'), AUTH_NO_REG))
           ..addRoute(
              name: 'home',
              path: '/home',
              enter: authView(router, view('home.html'), AUTH_AND_REG));
       }
    
       authView(Router router, ngView, mode) {
         return (RouteEvent e) {
           if (mode == AUTH_AND_REG) {
             if (!authService.isAuth) {
               router.go('login', {});
               return;
             }
             if (!authService.isReg) {
               router.go('register', {});
               return;
             }
           } else if (mode == AUTH_NO_REG) {
             if (!authService.isAuth) {
               router.go('login', {});
               return;
             }
             if (authService.isReg) {
               router.go('home', {});
               return;
             }
           } else if (mode == NOT_AUTH) {
             if (authService.isAuth) {
               router.go('register', {});
               return;
             }
           }
           ngView(e);
         };
       }
    

    }

    DISCLAMER: this is just an idea... might totally not work.

提交回复
热议问题