In the Angular project, I want to store the pages visited by the user in the user's local area and create a list of my recent visits. I tried this using both localStorage and sessionStorage, but I cannot access any URLs other than the router URLs defined in the project. What approach should I follow in this regard?
Firstly, you cannot access access Url's that are not defined in your Router
, because they're not actually handled by Angular. If that's what you're after, then I'd have to disappoint you with a simple 'It's not possible'.
However you can still use Router
to store any recent visits to the url's in your application:
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private router: Router) {}
ngOnInit() {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
this.storePage(event.urlAfterRedirects);
}
});
}
private storePage(url: string) {
let recentVisits = JSON.parse(localStorage.getItem('recentVisits') || '[]');
recentVisits.unshift(url);
localStorage.setItem('recentVisits', JSON.stringify(recentVisits));
}
}