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

And*_*ist 24 angular2-routing angular

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

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

我确实找到了一个关于这个的问题(和答案),但是对它没有任何意义. 登录后Angular2重定向

Fab*_*nes 43

Angular Docs中有一个很好的例子,教授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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 我会使用 `this.router.navigateByUrl(this.redirectUrl);` 来支持查询参数,否则这些参数会被修剪。 (3认同)

小智 6

此代码将处理您的请求:

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;
      });
  }
}
Run Code Online (Sandbox Code Playgroud)

但请注意,URL 参数不会与 URL 一起传递!!

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