在 Angular 中保存/恢复路由器状态

Sla*_* II 5 angular-routing angular

当用户到达我的应用程序中受特殊保护的路由时,我将他重定向到登录路由,以执行身份验证。

但是,在成功验证后,我不想将她重定向回她最初到达的路线。

如何在 Angular 中保留中间路由状态然后重定向到它?

通过路由状态,我的意思是:

  • 路线本身,即路径
  • 所有查询字符串参数
  • 一个哈希字符串

Deb*_*ahK 0

一种方法是使用服务。

这是一个示例服务:

import { Injectable } from '@angular/core';

import { IUser } from './user';
import { MessageService } from '../messages/message.service';

@Injectable()
export class AuthService {
    currentUser: IUser;
    redirectUrl: string;

    constructor(private messageService: MessageService) { }

    isLoggedIn(): boolean {
        return !!this.currentUser;
    }

    login(userName: string, password: string): void {
        if (!userName || !password) {
            this.messageService.addMessage('Please enter your userName and password');
            return;
        }
        if (userName === 'admin') {
            this.currentUser = {
                id: 1,
                userName: userName,
                isAdmin: true
            };
            this.messageService.addMessage('Admin login');
            return;
        }
        this.currentUser = {
            id: 2,
            userName: userName,
            isAdmin: false
        };
        this.messageService.addMessage(`User: ${this.currentUser.userName} logged in`);
    }

    logout(): void {
        this.currentUser = null;
    }
}
Run Code Online (Sandbox Code Playgroud)

完整代码在这里: https: //github.com/DeborahK/Angular-Routing

但如果你找不到它......这是登录组件代码:

import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Router } from '@angular/router';

import { AuthService } from './auth.service';

@Component({
    templateUrl: './app/user/login.component.html'
})
export class LoginComponent {
    errorMessage: string;
    pageTitle = 'Log In';

    constructor(private authService: AuthService,
                private router: Router) { }

    login(loginForm: NgForm) {
        if (loginForm && loginForm.valid) {
            let userName = loginForm.form.value.userName;
            let password = loginForm.form.value.password;
            this.authService.login(userName, password);

            if (this.authService.redirectUrl) {
                this.router.navigateByUrl(this.authService.redirectUrl);
            } else {
                this.router.navigate(['/products']);
            }
        } else {
            this.errorMessage = 'Please enter a user name and password.';
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

并且 authguard 服务已完成:

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot, Router, Route,
         CanActivate, CanActivateChild, CanLoad } from '@angular/router';

import { AuthService } from './auth.service';

@Injectable()
export  class AuthGuard implements CanActivate, CanActivateChild, CanLoad {

constructor(private authService: AuthService,
            private router: Router) { }

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    console.log('In canActivate: ' + state.url);
    return this.checkLoggedIn(state.url);
}

canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    console.log('In canActivateChild: ' + state.url);
    return this.checkLoggedIn(state.url);
}

canLoad(route: Route): boolean {
    console.log('In canLoad: ' + route.path);
    return this.checkLoggedIn(route.path);
}

checkLoggedIn(url: string): boolean {
    if (this.authService.isLoggedIn()) {
        return true;
    }

    // Retain the attempted URL for redirection
    this.authService.redirectUrl = url;
    this.router.navigate(['/login']);
    return false;
}
Run Code Online (Sandbox Code Playgroud)

}