每个页面上的angular2用户状态
Posted
技术标签:
【中文标题】每个页面上的angular2用户状态【英文标题】:angular2 user status on each page 【发布时间】:2017-01-17 07:48:07 【问题描述】:如何使用 angular2.0 跟踪每个页面上的访问者状态。我已经有一个基于 jwt 的身份验证,它工作正常,但现在我希望能够检查每个路由是否访问者登录。
我的服务提供商看起来像
import Injectable from '@angular/core';
import Http, Headers, Response from '@angular/http';
import Observable from 'rxjs/Observable';
import Configuration from '../app.constants';
@Injectable()
export class AuthenticationService
public token: string;
public loggedIn: boolean;
private actionUrl;
constructor(private http: Http, private _configuration: Configuration)
// set token if saved in local storage
var currentUser = JSON.parse(localStorage.getItem('currentUser'));
this.token = currentUser && currentUser.token;
if(this.token)
this.loggedIn = true;
this.actionUrl = _configuration.ServerWithApiUrl;
login(username, password): Observable<boolean>
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
var data = ("_username=" + username + "&_password="+ password );
return this.http.post(
this.actionUrl + 'login_check',
//JSON.stringify( _username: username, _password: password ),
data,
headers: headers
)
.map((response: Response) =>
// login successful if there's a jwt token in the response
let token = response.json() && response.json().token;
if (token)
// set token property
this.token = token;
// store username and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify( _username: username, token: token ));
// return true to indicate successful login
return true;
else
// return false to indicate failed login
return false;
);
logout(): void
// clear token remove user from local storage to log user out
this.token = null;
localStorage.removeItem('currentUser');
isLoggedIn()
return this.loggedIn;
还有我的路由器
import Routes, RouterModule from '@angular/router';
import Login from './login/';
import Signup from './signup/';
import FrontendComponent from './frontend/';
import Blog from './blog/';
import DashboardComponent from './dashboard/';
import Results from './filter/';
import AuthGuard from './common/auth.guard';
const appRoutes: Routes = [
path: 'login', component: Login ,
path: 'register', component: Signup ,
path: 'blog', component: Blog ,
path: '', component: FrontendComponent,
path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] ,
// otherwise redirect to home
path: '**', redirectTo: ''
];
export const routing = RouterModule.forRoot(appRoutes);
【问题讨论】:
【参考方案1】:查看路由上的 AuthGuard。基本上你可以像这样创建一个 authGuard:
// auth-guard.ts
import Injectable from '@angular/core';
import CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot from '@angular/router';
import LoginService from './login.service';
@Injectable()
export class AuthGuardService implements CanActivate
constructor(private ls: LoginService,
private router: Router)
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot)
if (this.ls.isLoggedIn)
return true;
this.router.navigate(['/login']);
return false;
然后像这样将它添加到您的路由中:
path: 'themes', loadChildren: './app/themes/themes.module#ThemesModule', canActivate: [ AuthGuardService ] ,
path: 'settings', loadChildren: './app/settings/settings.module#SettingsModule', canActivate: [ AuthGuardService ] ,
如果您在功能模块中有路由,则需要将其添加到您希望保护的路由中。
【讨论】:
以上是关于每个页面上的angular2用户状态的主要内容,如果未能解决你的问题,请参考以下文章