Angular 2 Cancelling Route Navigation on UnAuthenticate

前端 未结 3 1979
星月不相逢
星月不相逢 2021-01-16 09:27

I have an app, with 3 links: Home (/), Sign in (/user/sign-in) and User Detail (/user).

When user click Home, my app will be show content public

When user cl

相关标签:
3条回答
  • 2021-01-16 10:05

    I think you could extend router outlet to implement such processing. Something like this:

    @Directive({
      selector: 'auth-outlet'
    })
    export class AuthOutlet extends RouterOutlet {
      publicRoutes: any;
      private parentRouter: Router;
      private authService: AuthService;
      constructor(_elementRef: ElementRef, 
                _loader: DynamicComponentLoader, 
               _parentRouter: Router,
               @Attribute('name') nameAttr: string, 
               _authService: AuthService) {
        (...)
      }
    
      activate(oldInstruction: ComponentInstruction) {
        var url = this.parentRouter.lastNavigationAttempt;
        console.log('attemping to nav');
        if (!this.publicRoutes[url] && !this.authService.loggedIn){
          var newInstruction = new ComponentInstruction('Login', [], new RouteData(), Login, false, 1);
          return super.activate(newInstruction);
        } else {
          return super.activate(oldInstruction);
        }
      }
    }
    

    The activate method is called when a route will be displayed. You can add at this level your processing.

    You use this directive this way un your template:

    @Component({
      (...)
      template: '<auth-outlet></auth-outlet>',
      directives: [ AuthOutlet ]
    })
    (...)
    

    See these links for more details:

    • Angular 2 Authentication with child routes
    • https://auth0.com/blog/2016/01/25/angular-2-series-part-4-component-router-in-depth/

    Another option is to use the CanActivate decorator but it's per component and can't be applies globally.

    0 讨论(0)
  • 2021-01-16 10:08

    For this I'll implement authService concept and before accessing any protected route, I'll check whether user is authenticated or not.If user is not authenticated I'll redirect him to login page.There if you want cancel button too, the you can put cancel button in LOGIN Component and when you press it you can redirect user back to previous component by using CanActive hook in Login Component). Just try to learn this and if you want any further help i'm here.

    auth.ts

    import {Observable} from 'rxjs/Observable';
    
    export class Auth {
      constructor() {
        this.loggedIn = false;
      }
    
      login() {
        this.loggedIn = true;
      }
    
      logout() {
        this.loggedIn = false;
      }
    
      check() {
        return Observable.of(this.loggedIn);
      }
    }
    

    For further code check out,

  • this plunker which is nicely written for protected routes
  • This implementation will surely help you for your use-case.

0 讨论(0)
  • 2021-01-16 10:20

    An unofficial solution that I found to this is to throw a NavigationCancelingError through an observable or a promise. Angular's router will catch this error type, cancel the navigation, and reset the current route. For example, this can be done in a resolve like so:

    import { ActivatedRouteSnapshot, Resolve, Router } from '@angular/router';
    import { NavigationCancelingError } from '@angular/router/src/shared';
    import { Observable } from 'rxjs';
    
    export class CancelingResolve implements Resolve<any> {
        constructor(private router: Router) {}
    
        resolve(route: ActivatedRouteSnapshot): Observable<any> {
            this.router.navigate(['new-route']); // Router will navigate here after canceling the activated route.
            return Observable.throw(new NavigationCancelingError());
        }
    }
    

    Note: Works under Angular 2.3.1

    0 讨论(0)
  • 提交回复
    热议问题