每页上的angular2用户状态

时间:2016-09-09 08:11:07

标签: angular typescript jwt status

如何使用angular2跟踪每个页面上的访问者状态。我已经有一个基于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 个答案:

答案 0 :(得分:0)

查看路线上的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 ] },

如果您在功能模块中有路线,则需要将其添加到您希望保护的路线中。