How can we prevent users from changing URLs or accessing pages directly in Angular 7 without using authguard?

Hey there! I am trying to find a way to prevent users from accessing different pages by changing the URL, like in this https://i.sstatic.net/E2e3S.png scenario. Is there a method that can redirect the user back to the same page without using Authguard or any Modules?

I have a StackBlitz project that is currently not functioning as expected.

Check it out here!

Answer №1

When a user manually changes the URL, your application will be reloaded. You can implement some JavaScript hacks to write the URL before unloading and then restore it upon loading.

window.addEventListener('beforeunload', function(e) {
  localStorage.setItem("appUnloading", JSON.stringify({time: Date.now(), url: location.pathname}));
};
.....
export class RouteGuard {
  constructor(private router: Router) {}
  canActivate() {
    const appUnloadingState = localStorage.getItem("appUnloading");
    let time, url;
    if (appUnloadingState) {
      {time, url} = JSON.parse(appUnloadingState);
    }
     if (Date.now() - time < 10000) { // Assume page loads within 10 seconds
        return this.router.parse(url); // This may not work on older Angular versions. Use router.navigate instead
     }

  }
}

Answer №2

The double asterisk path in the final route acts as a wildcard. When the requested URL does not match any of the paths defined earlier in the configuration, the router will select this route. This can be utilized to show a "404 - Not Found" page or redirect to another route.

app.module:

import { HelloComponent } from './hello.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
const appRoutes: Routes = [
  { path: 'hello', component: HelloComponent },


  { path: '**', component: PageNotFoundComponent } <---
];
@NgModule({
  imports:      [ BrowserModule,RouterModule.forRoot(
      appRoutes,

    ), FormsModule ],
  declarations: [ AppComponent, HelloComponent, PageNotFoundComponent ],
  bootstrap:    [ AppComponent ]
})

https://stackblitz.com/edit/angular-ibrovt?file=src/app/app.module.ts

I trust this information is useful!

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

Different Zoom feature for JIT Graph

I'm currently working with the Java Infovis Toolkit and I'd like to use buttons for zooming in and out instead of using the mouse wheel. Can someone guide me on how I can implement two separate buttons for Zoom In and Zoom Out functions? ...

Axios mistakenly includes an additional trailing slash in body parameters

Currently, in the process of developing an application utilizing React Native, I am faced with the challenge of communicating with an IoT chip that possesses minimal RAM memory. Due to this constraint, all logic must be executed on the client side. One sp ...

React application facing a problem with bracket notation in Typescript

After creating a form state to store and update input changes, I encountered an issue: const [form, setForm] = useState({ user: '', email: '', password: '', }); I then wrote a function to handle form changes: const handle ...

Tips for aggregating the values of object arrays in React props

I need help sorting three top-rated posts. Currently, the function displays three post titles along with their ratings, but they are not sorted by best rating. Can anyone assist me with this issue? {posts.slice(0, 3).sort((a, b) => ...

Transferring documents from an angular ionic application to a slim php framework on the localhost

Hey there! I've got a project on my localhost where I need to upload files to a local folder. I'm sharing the code here in hopes that someone can assist me. HTML: <ion-item ion-item *ngFor="let item of lista" menuClose> Floor: ...

Google Cloud Platform (GCP) reported a Stripe webhook error stating that no matching signatures were found for the expected signature

Current Stripe version: "8.107.0" I am encountering an issue with Stripe webhook verification whenever I deploy my webhook on Google Cloud Platform (GCP). Despite trying various methods to include the raw body in the signature, including the cod ...

Unable to assign an IP address to an Express JS application

Struggling to test a specific endpoint in Express, but consistently encountering a 404 error. var express = require("express") var app = express() //var http = require('http').Server(app) app.get('/', function(req,res){ res. ...

What is the best way to restrict the degree of camera rotation in the left, right, up, and down directions in Three.js when using a

Although this question may have been asked before, I haven't been able to find a solution to my specific issue! I've set up a 3D canvas using WebGLRenderer, PerspectiveCamera, and OrbitControls. My camera's position is at 0, 10, 500 for the ...

Tips for incorporating a plugin and utilizing an external module or file on RT

My node.js application/module is currently functioning well with a plug-in concept. This means that my module acts like a proxy with additional capabilities, such as adding new functionality to the existing methods. To achieve this, follow these steps: Cl ...

Exploring the capabilities of the Vuejs EventBus

I've been struggling with this issue for quite some time now, but I just can't seem to get it right! I've looked at various examples online, but none of them seem to solve the problem. Every time I run my test, I keep getting this error: Ex ...

AngularJS directive element not displaying CSS styles properly

I've been grappling with this issue for the past few days and I just can't seem to crack it. Whenever I try adding a class to an AngularJS element directive, the styling appears in the code view of my browser (Chrome), but the styles themselves ...

Why are XAxis categories appearing as undefined in tooltip when clicked?

[When clicking on the x-axis, the values go from 0 to 1. I need the x-axis categories values to display on click event. When hovering over the x-axis value, it shows properly, but clicking on the x-axis does not show the correct values] Check out this fid ...

You cannot assign a promise to a React state

Calling a function from MoviesPage.tsx to fetch movie data results in a promise containing an object that is successfully fetched (can confirm by console logging). However, I'm facing an issue when trying to assign the result to a state - receiving a ...

Steps to retrieve a specific key value from each object in an AJAX request

I am looking to extract the "url" key and its value from the provided code and save it in a variable. I have attempted different methods to isolate the url key as seen in my commented-out code. $.ajax({ type: 'GET', url: "url", // data: da ...

Two events can be triggered with just one button press

Is there a way to trigger two functions with just one button click? I want the button to execute the check() function and open a popup window with a PHP script. I've tried different approaches but none have been successful. Can anyone assist me? < ...

The Power of jQuery's .ajax() Utility

I'm a beginner with the jQuery AJAX ajax() Method and have recently created the AddATeacher() function. The function gets called successfully as I see all the alert messages popping up. However, the ajax() Method within the function is not working. Th ...

What is the best method for efficiently loading SVG icons on an HTML page without redundancy? / Is utilizing <use href> recommended?

My struggle with implementing icons in Angular While working on a new Angular project, I've encountered challenges with my current SVG-icon implementation method from a previous project (@ngneat/svg-icon). The process involves organizing SVG files in ...

NextAuth - simulating the login process of OneLogin

I've been working on setting up a local OneLogin mocked service using WireMock. Everything has been going smoothly so far, as I was able to mock most of the OAuth OneLogin flow. However, I'm facing an issue with the last part that is preventing i ...

In what way can TS uniquely handle each element of an array as the key of an object?

I am struggling with an object that I need to have keys representing every item in the array, each linked to a value of any. Can anyone provide guidance on how to achieve this? Unfortunately, I couldn't find a solution. Here is an example for refere ...

Verification of Form Submission

Looking for some help with web design, specifically regarding cache issues. I have a website where form data is submitted from form.php to buy-form.php. I'm trying to set up a cache error in Google Chrome so that when buy-form.php is accessed directl ...