且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-10-25 23:36:46

Angular Docs中有一个很好的例子,

There's a great example in the Angular Docs, Teach Authguard To Authenticate. Basically the idea is using your AuthGuard to check for your login status and store the url on your AuthService. Some of the code is on the url above.

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

AuthService or your 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;
  }
}

我认为这可以让您了解事情的工作原理,当然您可能需要适应您的代码

I think this will give an idea how things work, of course you probably need to adapt to your code