javascript - Angular 路由,包括身份验证防护和重定向

标签 javascript angular typescript url-routing angular-routing

我有一个 Angular 应用程序,想要实现客户端路由。我有 3 个组件:loginchatadmin。对管理和聊天的访问受到身份验证守卫的限制。理想情况下,路由行为应该是:

  • 点击登录 -> 路由登录并重定向至管理员
  • 点击管理或聊天 -> 路由登录并在成功登录后重定向到所点击的内容(分别为管理或聊天)

我设法将重定向设置得几乎正确,但是单击登录时的重定向仍然取决于我之前/最后单击的位置。这意味着,如果用户单击登录,它将转到登录,成功登录后,它将重定向到聊天。然后用户注销并单击登录,它会登录但重定向到聊天而不是管理员,这是我不想要的。无论过去哪条路线处于事件状态,点击登录都应始终转到管理员。

我怎样才能实现这个目标?

谢谢。

应用程序组件

<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;
      let redirect = this.authService.redirecturl ? this.router.parseUrl(this.authService.redirecturl) : '/admin';
      this.router.navigateByUrl(redirect);  
    });
  }

  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() {
  }

}

authgauard

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 { }

身份验证服务

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { throwError, Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  redirecturl: string; // used for redirect after successful login
  username: string;
  loginMessage: string;
  greeting = 'Hello guest!';
  loggedIn = false;
  config = {
    serverHost: 'localhost',
    serverPort: 3000,
    loginRoute: 'login',
    standardGreeting: `Hello guest!`,
    standardUsername: 'Guest'
  };

  constructor(private http: HttpClient) { }

  login(loginUrl: any, body: { pass: string }) {
    return this.http.post(loginUrl, body, httpOptions)
      .pipe(
        catchError(this.handleError)
      );
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      console.error('An error occurred:', error.error.message);
    } else {
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    return throwError(
      'Something bad happened; please try again later.');
  }

  isLoggedIn(): boolean {
    return this.loggedIn;
  }
  }
}

最佳答案

而不是这样做 <button (click)="login()" routerLink="/admin" routerLinkActive="active">Login</button>在 html 中将重定向网址放入 typescript 中,如下所示。

    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,否则它将始终重定向到上次访问的页面。

编辑

在 App.component.html 中,您将使用 routerlink 导航登录,而不是使用此链接

<nav>
  <ol>
    <li><a (click)='redirectToLogin()'>Login</a></li>
    <li><a routerLink="/admin">Admin</a></li>
    <li><a routerLink="/chat">Chat</a></li>
  </ol>
</nav>
<router-outlet></router-outlet>

并在app.component.ts中使用这个

redirectToLogin(){
    this.authService.redirectUrl = null;
    this.router.navigateByUrl('/login');
}

关于javascript - Angular 路由,包括身份验证防护和重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59784463/

相关文章:

angular - 使用 angular4 构建渐进式 Web 应用程序。

javascript - 返回一个包含来自 Observable<{string; 的响应的数组数字;字符串;}[]>

angular - Ngx-datatable 行详细信息

javascript - 将光标设置在 div 元素上?

javascript - Knockout observablearry 不具有约束力

javascript - 如何在加载 JSON 之前隐藏 Knockout.js 中的 div?

c# - 在 MVC 中使用 AngularJs 时保持 View 的强类型

javascript - Bootstrap 3 Glyphicon 未在下拉菜单中对齐

javascript - 以响应式表单提交读取属性值

javascript - 单击后在 Json 上创建一个新对象(http.put)