我有一个角度应用程序,想实现客户端路由。我有3个组成部分:login
,chat
和admin
。管理员和聊天功能受身份验证防护措施的限制。理想情况下,路由行为应为:
我设法设置重定向几乎正确,但是单击登录时的重定向仍然取决于我之前/最后单击的位置。这意味着,如果用户单击登录,它将转到登录,成功登录后,它将重定向到聊天。然后,用户注销并单击“登录”,它将进入登录状态,但重定向到聊天而不是“管理员”,我不希望这样。无论过去哪个路由处于活动状态,登录时的点击次数都应始终设为管理员。
我该如何实现?
谢谢。
<nav>
<ol>
<li><a routerLink="/login">Login</a></li>
<li><a routerLink="/admin">Admin</a></li>
<li><a routerLink="/chat">Chat</a></li>
</ol>
</nav>
<router-outlet></router-outlet>
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
}
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import {AuthService} from "../auth.service";
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
email: string;
password: string;
loginMessage: string;
loginForm: FormGroup;
constructor(
private http: HttpClient,
) { }
ngOnInit() {
this.loginForm = new FormGroup({
'email': new FormControl(this.email, [
Validators.required,
Validators.email
]),
'password': new FormControl(this.password, [
Validators.required,
Validators.minLength(2)
])
});
console.log('init');
}
logout(): void {
this.authService.loggedIn = false;
}
login(): void {
if (!this.isValidInput()) { return; }
const data = {email: this.email, pass: this.password};
this.authService.login('localhost:3000/login', data).subscribe((response: any) => {
this.loginForm.reset();
this.authService.loggedIn=true;
});
}
isValidInput(): Boolean {
if (this.loginForm.valid) {
this.email = this.loginForm.get('email').value;
this.password = this.loginForm.get('password').value;
return true;
}
return false;
}
}
<form [formGroup]="loginForm">
<!-- this div is just for debugging purpose -->
<div id="displayFormValues">
Value: {{loginForm.value | json}}
</div>
<label for="email"><b>Email</b></label>
<input id="email" type="email" formControlName="email" email="true" required>
<label for="password"><b>Password</b></label>
<input id="password" type="password" formControlName="password" required>
<button (click)="login()" routerLink="/admin" routerLinkActive="active">Login</button>
<div id="loginMessage">{{loginMessage}}</div>
</form>
<p>admin works!</p>
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-admin',
templateUrl: './admin.component.html',
styleUrls: ['./admin.component.css']
})
export class AdminComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
<p>chat works!</p>
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-chat',
templateUrl: './chat.component.html',
styleUrls: ['./chat.component.css']
})
export class ChatComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
import { Injectable } from '@angular/core';
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor() {
}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
let url: string = state.url;
if (this.authService.isLoggedIn()) {
return true;
} else {
this.authService.redirecturl = url;
this.router.navigate(['/login']);
return false;
}
}
}
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ChatComponent } from './chat/chat.component';
import { AdminComponent } from './admin/admin.component';
import { LoginComponent } from './login/login.component';
import { AuthGuard } from './auth.guard';
const routes: Routes = [
{
path: 'login',
component: LoginComponent
},
{
path: 'admin',
component: AdminComponent,
canActivate: [AuthGuard]
},
{
path: 'chat',
component: ChatComponent,
canActivate: [AuthGuard]
}
];
@NgModule({
imports: [RouterModule.forRoot(routes, {enableTracing: true})],
exports: [RouterModule]
})
export class AppRoutingModule { }
而不是在HTML中执行此<button (click)="login()" routerLink="/admin" routerLinkActive="active">Login</button>
,而是在这样的打字稿中放置重定向URL。
login(): void {
if (!this.isValidInput()) { return; }
const data = {email: this.email, pass: this.password};
this.authService.login('localhost:3000/login', data).subscribe((response: any) => {
if(response.isSuccess){
this.loginForm.reset();
this.authService.loggedIn=true;
if(!this.authService.redirectUrl){
this.router.navigateByUrl('/admin');
} else{
this.router.navigateByUrl(this.authService.redirectUrl);
}
}
});
}
并且如果您要导航到登录URL,请以其他方式删除redirectUrl,它将始终重定向到上次访问的页面。