How can I implement visitor status tracking for every page in angular2? I have a jwt based authentication system in place that is working correctly, but now I need to ensure that the visitor's login status is checked on each route.
Here is an example of my service provider:
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) {
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',
data,
{ headers: headers }
)
.map((response: Response) => {
let token = response.json() && response.json().token;
if (token) {
this.token = token;
localStorage.setItem('currentUser', JSON.stringify({ _username: username, token: token }));
return true;
} else {
return false;
}
});
}
logout(): void {
this.token = null;
localStorage.removeItem('currentUser');
}
isLoggedIn() {
return this.loggedIn;
}
}
Here is my router configuration:
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] },
{ path: '**', redirectTo: '' }
];
export const routing = RouterModule.forRoot(appRoutes);