Angular - How to return to last page


This is how to "remember" and return to the last viewed page in an Angular app.

Imagine if your Angular app would "remember" the last page your users visited before they closed their browser tab.

And next time they opened your app...

It would magically...

Return them to where they had previously left off.

😌 😌 😌

Depending on your Angular project there really isn't much benefit in doing this.

But for others this might be a tiny feature you can add to your Angular app to make your users coo and aah. 🤓

how-neat-is-that

So why not do it?

We have two options.

  1. Use an existing Angular library to do this for us.
  2. Create the functionality ourselves and skip the library.

The first option is the easiest so I'll show you how to do it that way first.

But if you'd rather choose the second path, then we'll dive into how to create the functionality by yourself without depending on a library created by someone else.

(Easy Way) Using ngx-pagememory to load the last page

First, we'll have to install the package.

npm install ngx-pagememory

And once installed, all we have to do is import the NgxPagememoryModule into the app.module.ts file like this.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { NgxPagememoryModule } from 'ngx-pagememory';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent    
  ],
  imports: [
    BrowserModule,
    NgxPagememoryModule.forRoot(),
    AppRoutingModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Wooooola!

You're done.

But what if you'd rather do this yourself?

Then, buster, keep reading and I'll show you the sauce.

1. Create the location memory module

The first step is to grab the Angular CLI and generate a new module.

ng generate module page-memory

2. Creating the route location service

Our new module is now ready for its own service to save and retrieve the routing history of our Angular application. So we'll generate a service that subscribes to the Angular router which allows us to keep track of the last page that was visited.

ng generate service page-memory/location-memory

And here's the code for our humble location memory service.

import { Injectable } from '@angular/core';
import { Router, RouterEvent } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class LocationMemoryService {

  lastRouteKey = "lastRoute";
  _lastRoute = localStorage.getItem(this.lastRouteKey);

  constructor(private router: Router) { }

  register(): void {
    let lastRoute = this.getLastRoute();
    if (lastRoute != null) {
      this.router.navigateByUrl(lastRoute);
    }

    this.router.events.subscribe((event: RouterEvent) => {
      if (event.url)
        this.setLastRoute(event.url);
    });
  }

  public setLastRoute(value: string) {
    localStorage.setItem(this.lastRouteKey, value);
  }

  public getLastRoute(): string | null {
    return localStorage.getItem(this.lastRouteKey);
  }
}

3. (Last Step) Preparing and importing the module

Our module is almost ready to be used. We only lack one more thing - registering our LocationMemoryService.

import { CommonModule } from '@angular/common';
import { APP_INITIALIZER, ModuleWithProviders, NgModule } from '@angular/core';
import { Router } from '@angular/router';
import { LocationMemoryService } from './location-memory.service';

@NgModule({
  declarations: [],
  imports: [
    CommonModule
  ],
})
export class LocationMemoryModule { 

  public static forRoot(): ModuleWithProviders<LocationMemoryModule> {
    return {
      ngModule: LocationMemoryModule,
      providers: [
        {
          provide: APP_INITIALIZER,
          deps: [LocationMemoryService, Router],
          useFactory: (pM: LocationMemoryService) => () => pM.register(),
          multi: true
        }
      ]
    }
  }

}

So what have we just done?

We've declared a public forRoot function inside the module that will initialize the location memory service when called.

All you need to do yet is import and hook it up inside of the app.module.ts file like this.

// Your imports here

@NgModule({
  declarations: [
    AppComponent    
  ],
  imports: [
    BrowserModule,
    NgxPagememoryModule.forRoot(),
    AppRoutingModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Routing to a conclusion

And that, my friend, is how to return to the last page and let your users start where they left off.

What approach did you use? The library or the code-it-yourself way?

Drop a comment below and let me know.

For now, I'm gonna route my way to the coffee machine.

signature

Angular Consultant