Angular2 – 成功登录后重定向到调用url
发布时间:2020-12-17 08:01:07 所属栏目:安全 来源:网络整理
导读:我的应用程序已启动并运行Angular 2.1.0. 路由受路由器保护,canActivate保护. 当将浏览器指向像“localhost:8080 / customers”这样的受保护区域时,我会像预期的那样重定向到我的登录页面. 但是在成功登录后,我希望被重定向回调用URL(在这种情况下为“/ cus
我的应用程序已启动并运行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. 我确实找到了一个关于这个的问题(和答案),但实际上对它没有任何意义.
在Angular Docs,Teach Authguard To Authenticate中有一个很好的例子.基本上,我们的想法是使用你的AuthGuard来检查你的登录状态并将你的网址存储在你的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; } } 我认为这会让人知道事情是如何运作的,当然你可能需要适应你的代码 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |