Check if the user logged in on any page change in Angular 2

后端 未结 4 1079
Happy的楠姐
Happy的楠姐 2020-12-15 00:00

Slowly but surely progressing with Angular2. And now I faced the following challenge. I want to check if the user logged in or not on every page change (in other words on lo

4条回答
  •  时光取名叫无心
    2020-12-15 00:13

    I think extending RouterOutlet is a common way to achive this

    Example posted a while ago in Gitter by CaptainCodeman (not tested myself yet)

      import {Directive, Injector, Attribute, ElementRef, DynamicComponentLoader} from 'angular2/core';
      import {Router, RouteData, RouterOutlet, RouteParams, Instruction, ComponentInstruction} from 'angular2/router';
    
      /*
        Example implementation
    
        Given a route:
        @RouteConfig([
        { path: '/thing/:id', component: ThingComponent, name: 'Thing', data: { public: false, roles:['thinger'] } }
        ])
    
        authorize(instruction: ComponentInstruction):boolean {
          // simplest case - route is public
          if (instruction.routeData.data['public']) {
            return true;
          }
    
          // if not public then we at least need an authenticated user
          if (this.isAuthenticated()) {
            var routeRoles = instruction.routeData.data['roles'];
            var userRoles = this.roles();
    
            // no roles required for route = user just needs to be authenticated
            var authorized = routeRoles.length === 0 || routeRoles.some(routeRole => userRoles.indexOf(routeRole) >= 0);
    
            return authorized;
          }
    
          return false;
        }
      */
    
      export abstract class IAuthService {
        abstract isAuthenticated():boolean;
        authorize(instruction: ComponentInstruction, params:any):boolean {
          // authorized if route allows public access or user is authenticated
          return this.isAuthenticated() || instruction.routeData.data['public']
        }
      }
    
    @Directive({selector: 'secure-outlet'})
      export class SecureRouterOutlet extends RouterOutlet {
        signin:string;
        unauthorized:string;
        injector:Injector;
    
        private parentRouter: Router;
        private authService: IAuthService;
    
        constructor(_elementRef: ElementRef, _loader: DynamicComponentLoader,
                    _parentRouter: Router, @Attribute('name') nameAttr: string,
                    authService:IAuthService,
                    injector:Injector,
                    @Attribute('signin') signinAttr: string,
                    @Attribute('unauthorized') unauthorizedAttr: string) {
          super(_elementRef, _loader, _parentRouter, nameAttr);
          this.parentRouter = _parentRouter;
          this.authService = authService;
          this.injector = injector;
          this.signin = signinAttr;
          this.unauthorized = unauthorizedAttr;
        }
    
        activate(nextInstruction: ComponentInstruction): Promise {
          var params = this.getAllRouteParams(this.injector);
          var isAuthorized = this.authService.authorize(nextInstruction, params);
    
          if (isAuthorized) {
            return super.activate(nextInstruction);
          }
    
          if (this.authService.isAuthenticated()) {
            var ins = this.parentRouter.generate([this.unauthorized]);
            return super.activate(ins.component);
          } else {
            var ins = this.parentRouter.generate([this.signin,{url:location.pathname}]);
            return super.activate(ins.component);
          }
        }
    
        reuse(nextInstruction: ComponentInstruction): Promise {
          return super.reuse(nextInstruction);
        }
    
        getAllRouteParams(injector) {
          let params = null;
          while(injector) {
            const routeParams = injector.getOptional(RouteParams);
            if (routeParams) {
              if (params === null) {
                params = {};
              } else {
                params = Object.create(params);
              }
    
              Object.assign(params, routeParams.params);
            }
            injector = injector.parent;
          }
          return params;
        }
      }
    

提交回复
热议问题