Using Angular2, how to redirect to previous url before login redirect

前端 未结 4 1632
说谎
说谎 2020-12-31 03:29

Using Angular2 to create a single page app, I\'m intercepting unauthenticated user access to non-public routes in a custom RouterOutlet and redirecting them to

4条回答
  •  鱼传尺愫
    2020-12-31 04:05

    Updated Example Using Angular 2.2.1

    Auth Guard that passes original URL to login component:

    import { Injectable } from '@angular/core';
    import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
    
    @Injectable()
    export class AuthGuard implements CanActivate {
    
        constructor(private router: Router) { }
    
        canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
            if (localStorage.getItem('currentUser')) {
                // logged in so return true
                return true;
            }
    
            // not logged in so redirect to login page with the return url
            this.router.navigate(['/login', { returnUrl: state.url }]);
            return false;
        }
    }
    
    import { Component, OnInit } from '@angular/core';
    import { Router, ActivatedRoute } from '@angular/router';
    
    import { AlertService, AuthenticationService } from '../_services/index';
    
    @Component({
        moduleId: module.id,
        templateUrl: 'login.component.html'
    })
    

    Login Component that redirects to the previous / original URL after login:

    export class LoginComponent implements OnInit {
        model: any = {};
        loading = false;
        returnUrl: string;
    
        constructor(
            private route: ActivatedRoute,
            private router: Router,
            private authenticationService: AuthenticationService,
            private alertService: AlertService) { }
    
        ngOnInit() {
            // reset login status
            this.authenticationService.logout();
    
            // get return url from route parameters or default to '/'
            this.returnUrl = this.route.snapshot.params['returnUrl'] || '/';
        }
    
        login() {
            this.loading = true;
            this.authenticationService.login(this.model.username, this.model.password)
                .subscribe(
                    data => {
                        // login successful so redirect to return url
                        this.router.navigate([this.returnUrl]);
                    },
                    error => {
                        // login failed so display error
                        this.alertService.error(error);
                        this.loading = false;
                    });
        }
    }
    

    For more details and working demo you can check out this post

提交回复
热议问题