Angular2 - 成功登录后重定向到调用网址

2023-11-24

我已经使用 Angular 2.1.0 启动并运行了我的应用程序。 路由通过路由器守卫 canActivate 进行保护。

当将浏览器指向“localhost:8080/customers”等受保护区域时,我会像预期一样重定向到我的登录页面。

但成功登录后,我想重定向回调用 URL(在本例中为“/customers”)。

处理登录的代码如下所示

login(event, username, password) {
  event.preventDefault();
  var success = this.loginService.login(username, password);
  if (success) {
    console.log(this.router);
    this.router.navigate(['']);
  } else {
    console.log("Login failed, display error to user");
  }
}

问题是,我不知道如何从登录方法内部获取调用 URL。

我确实找到了一个与此相关的问题(和答案),但无法真正理解它。Angular2 登录后重定向


Angular 文档中有一个教程,里程碑 5:路线守卫。实现此目的的一种可能方法是使用 AuthGuard 检查您的登录状态并将 URL 存储在 AuthService 上。

验证卫士

import { Injectable }       from '@angular/core';
import {
  CanActivate, Router,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
}                           from '@angular/router';
import { AuthService }      from './auth.service';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    let url: string = state.url;

    return this.checkLogin(url);
  }

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

    // Store the attempted URL for redirecting
    this.authService.redirectUrl = url;

    // Navigate to the login page with extras
    this.router.navigate(['/login']);
    return false;
  }
}

认证服务或您的登录服务

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Router } from '@angular/router';

@Injectable()
export class AuthService {
  isLoggedIn: boolean = false;    
  // store the URL so we can redirect after logging in
  public redirectUrl: string;

  constructor (
   private http: Http,
   private router: Router
  ) {}

  login(username, password): Observable<boolean> {
    const body = {
      username,
      password
    };
    return this.http.post('api/login', JSON.stringify(body)).map((res: Response) => {
      // do whatever with your response
      this.isLoggedIn = true;
      if (this.redirectUrl) {
        this.router.navigate([this.redirectUrl]);
        this.redirectUrl = null;
      }
    }
  }

  logout(): void {
    this.isLoggedIn = false;
  }
}

我认为这将让您了解事情是如何工作的,当然您可能需要适应您的代码

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular2 - 成功登录后重定向到调用网址 的相关文章

随机推荐