Angular2 display user's activity status on every individual page

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);

Answer №1

Take a look at using AuthGuard for securing routes. Essentially, you can create an authGuard in the following way:

// custom-auth-guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

import { LoginService } from './login.service';

@Injectable()
export class CustomAuthGuard implements CanActivate {

  constructor(private loginService: LoginService, 
              private router: Router) {}

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (this.loginService.isLoggedIn) {
      return true;
    }

    this.router.navigate(['/login']);
    return false;
  }
}

Afterward, integrate it into your routing configuration like so:

{ path: 'themes', loadChildren: './app/themes/themes.module#ThemesModule', canActivate: [ CustomAuthGuard ] },
{ path: 'settings', loadChildren: './app/settings/settings.module#SettingsModule', canActivate: [ CustomAuthGuard ] },

Remember to include the authGuard in feature modules as well if you want to protect specific routes within them.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can one use an Angular Route to navigate to a distinct URL? Essentially, how does one disable matching in the process?

I'm working on a front-end Angular application and I need to add a menu item that links to an external website. For example, let's say my current website has this URL: And I want the menu item in my app to lead to a completely different website ...

How to display the Y axis value on the category axis in a solid gauge using amcharts

My Code : <div id="chartdiv"></div> Styling : #chartdiv { width: 100%; height: 200px; } Script: am4core.useTheme(am4themes_animated); var chart = am4core.create("chartdiv", am4charts.RadarChart); chart.data = [{ ...

Error: Typescript error at line 18 in app.ts - Cannot locate the 'server' namespace

Check out this straightforward code snippet: "use strict"; import * as express from "express"; class Server { public app: express.Application; public static start(): Server { return new Server(); } constructor() { this. ...

Problem with JWT authentication causing SockJS handshake to block WebSocket connection attempts

I have an operational Spring Boot server with Authentication/Authorization features. However, I am facing issues when trying to establish a connection with SockJS due to my security protocols blocking it. Although I do not have a complete understanding of ...

Quick tip: Showing a default Font Awesome icon in Vue, Angular, or React when the desired icon is not found

Utilizing the <fa-icon> fontawesome component, I implement the library approach as follows: export const faIconsDefinitionsToRegister: IconDefinition[] = [ ...proRegularFaIcons, ...proSolidFaIcons, ...proLightFaIcons, ...proThinFaIcons, ... ...

Unlock the power of the multiselect dropdown component in MUI with direct access

I'm intrigued by the multi-select capabilities of the MUI Select component when using the multiple=true option. However, rather than having a traditional dropdown menu, I want to integrate the selection options directly into a div on the page. I prefe ...

Bring in a class with an identical name to a namespace

Currently, I am utilizing a third-party library that comes with a separate @types definition structured as follows: declare namespace Bar { /* ... */ } declare class Bar { /* ... */ } export = Bar; How should I go about importing the Bar class into my ...

Typescript | The extension of formikProps on IProps in Typescript is lacking 27 Props

I'm currently working with Formik in TypeScript and I'm trying to integrate a simple form component into TS within another component where I extract the defaultValues and validationSchemas. The challenge lies in accessing only the necessary form ...

Dealing with Angular 6 HTTP Interceptor and the frustrating net:: ERR_TIMED_OUT error

I have been puzzling over something recently that has left me scratching my head. Within my interceptor, there is code that deals with parsing and handling errors in specific ways based on factors such as status codes. While I haven't included this c ...

Utilizing Gulp to Convert TypeScript Exports into a JSON File

I have a set of TypeScript files, some of which export a specific variable - named APIS - which contains an array of objects. My goal is to extract the values from all of these exports and save them into a JSON file using Gulp. Let's consider a direc ...

Ways to modify the appearance of the button within ion-calendar

Looking to customize the styling of ion-calendar classes Attempting to add styles to the ion-calendar-month class, but not seeing any changes take effect. ...

Utilize Angular2 to dynamically add new routes based on an array register

Currently, I am utilizing Angular2 for the frontend of my project and I am faced with the task of registering new Routes from an array. Within my application, there is a service that retrieves data from a server. This data is then stored in a variable wit ...

Find out if all attributes of the object are identical

I am trying to create the boolean variable hasMultipleCoverageLines in order to determine whether there are multiple unique values for coverageLineName within the coverageLines items. Is there a more efficient way to write this logic without explicitly c ...

Alter text within a string situated between two distinct characters

I have the following sentence with embedded links that I want to format: text = "Lorem ipsum dolor sit amet, [Link 1|www.example1.com] sadipscing elitr, sed diam nonumy [Link 2|www.example2.com] tempor invidunt ut labore et [Link 3|www.example3.com] m ...

Issue encountered in Angular 2 while attempting to import TypeScript classes using a single file

Upon loading my Angular 2 application, I encountered the following error: EXCEPTION: Error: Uncaught (in promise): Unexpected piped value 'undefined' on the View of component 'DashboardComponent' An interesting observation is that by ...

Next.js v13 and Firebase are encountering a CORS policy error which is blocking access to the site.webmanifest file

Background: I am currently developing a website using Next.js version 13 in combination with Firebase, and I have successfully deployed it on Vercel. Upon inspecting the console, I came across two CORS policy errors specifically related to my site.webmani ...

Angular - postpone function execution until Subject has completed its operation

In my code, there is a function that stops a running process using a specified processId. Before this function is executed, there is a single if statement that checks if a valid processId exists, and if so, it calls the cancel() function. if (this.process ...

Beware: The use of anonymous arrow functions in Next.js can disrupt Fast Refresh and lead to the loss of local component state

I am currently encountering a warning that is indicating an anonymous object in a configuration file, and even specifying a name for it does not resolve the warning. Below you will find the detailed warning message along with examples. Warning: Anonymous ...

Determine if the current page is the root page in Ionic 2 - here's how!

Currently, I am trying to verify the name of the current page in Ionic 2. To achieve this, I utilized NavController in my app.component.ts file. However, an error stating No provider for NavController is being displayed. I would appreciate any suggestions ...

Angular library generation causing circular dependencies

Modification Required It has come to my attention that the issue of a circular dependency arises solely when utilizing a production build - ng build lib --prod My task involves creating an Angular library intended for utilization in a separate Angular pr ...