首页 文章

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

提问于
浏览
13

我的应用程序已启动并运行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");
  }
}

问题是,我不知道如何从login方法中获取调用url .

我确实找到了一个关于这个的问题(和答案),但实际上对它没有任何意义 . Angular2 Redirect After Login

2 回答

  • 28

    在Angular Docs中有一个很好的例子,Teach Authguard To Authenticate . 基本上,这个想法是使用您的AuthGuard来检查您的登录状态并将URL存储在您的AuthService上 . 一些代码在上面的url上 .

    AuthGuard

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

    AuthService 或您的LoginService

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

    我认为这会让人知道事情是如何运作的,当然你可能需要适应你的代码

  • 1

    此代码将处理您的请求:

    export class AuthGuard implements CanActivate {
      constructor(private authService: AuthService,
                  private router: Router) {
      }
    
      canActivate(next: ActivatedRouteSnapshot,
                  state: RouterStateSnapshot): Observable<boolean> {
        return this.authService.isVerified
          .take(1)
          .map((isVerified: boolean) => {
            if (!isVerified) {
              this.router.navigate(['/login'], {queryParams: {returnUrl: state.url}});
              return false;
              // return true;
            }
            return true;
          });
      }
    }
    

    但要注意URL params不会传递URL!

    你可以在这里找到一个很好的教程:http://jasonwatmore.com/post/2016/12/08/angular-2-redirect-to-previous-url-after-login-with-auth-guard

相关问题