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

Encountering an issue while executing the installation command

Feeling frustrated and confused about the Error message appearing, despite trying to run the command as Administrator. npm ERR! Windows_NT 6.1.7601 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Fi ...

"Send the selected radio button options chosen by the user, with the values specified in a JSON format

My current task involves inserting radio button values into a MySql database using Angular. The form consists of radio buttons with predefined values stored in a json file. Below is an example of how the json file is structured: //data.json [{ "surve ...

Adding files to an Angular ViewModel using DropzoneJS

I am facing a challenge in extracting file content and inserting it into a specific FileViewModel. This is necessary because I need to bundle all files with MainViewModel which contains a list of FileViewModel before sending it from the client (angular) to ...

I'm perplexed as to why my JavaScript code isn't successfully adding data to my database

Recently, I delved into the world of NodeJS and Express. My goal was to utilize Node and Express along with MongoDB to establish a server and APIs for adding data to the database. Specifically, I aimed to write the code in ESmodules syntax for JavaScript. ...

auto-scrolling webpage as elements come into view

Here is some jQuery code I have: $(".col-md-12").hide(); $(".button-div").hide(); $(".featurette-divider").hide(); $(".footer").hide(); $(".first").fadeIn(1000); $(".second").delay(900).fadeIn(1000); $(".third").delay(1800).fadeIn(1000); $(".fourth").dela ...

Unable to display information stored in the Firebase database

I am struggling with a frustrating issue. My goal is to showcase the information stored in the Firebase database in a clear and organized manner, but I'm having trouble achieving this because it's being treated as an object. getData(){ firebas ...

Exploring the Capabilities of TypeScript 1.8 in Visual Studio 2017

Recently, I've encountered an issue with my Visual Studio project that was created using TypeScript 1.8 in Visual Studio 2015. Upon upgrading to Visual Studio 2017 and attempting to open the project in the new IDE, I noticed that the TypeScript versio ...

What's the reason for text-alignment not functioning properly?

After some testing, I have come up with the following code: .Greetings { width:100%; display:block; text-align:center; font-family: "Times New Roman", Times, serif; font-size:75px; color:#208CB7; } The objective was to center the text on the ...

Tips for uploading images, like photos, to an iOS application using Appium

I am a beginner in the world of appium automation. Currently, I am attempting to automate an iOS native app using the following stack: appium-webdriverio-javascript-jasmine. Here is some information about my environment: Appium Desktop APP version (or ...

Stop the selection of text within rt tags (furigana)

I love incorporating ruby annotation to include furigana above Japanese characters: <ruby><rb>漢</rb><rt>かん</rt></ruby><ruby><rb>字</rb><rt>じ</rt></ruby> However, when attemp ...

registering a back button action in Ionic2 for multiple pages

Currently, I am in the process of developing my Ionic2 app and have encountered a dilemma regarding the functionality of registerBackButtonAction. On one page, let's call it pageA, I have implemented this function and everything is functioning as exp ...

Setting up button value dynamically according to dropdown selection in Angular 2

I'm a beginner in angular 2 and I have a button with a dropdown. When I select an option from the dropdown, I want its value to be displayed on the button. The CSS code for styling the dropdown is provided below: .common_select_box { width: 100%; } ...

Uploading files using Angular 6 to communicate with a Flask (Python) API

I have developed a web service using Flask to save files, following the example provided in the official Flask documentation: @app.route('/parse_table', methods=['POST']) def upload_file(): print(request.files) # check if the p ...

Is there a way to adjust the brightness of specific sections within an image using html, css, and js?

I am working on a project where I have an image with tags underneath that correspond to different parts of the image. For example, if the image is of a dog, one of the tags could be 'nose', indicating the portion of the image around the dog' ...

How can I retrieve the ngx-Summernote runtime value?

I am currently integrating ngx-Summernote into my Ionic 5 + Angular project. Is there a way to access the value using ngModel? I attempted: <div [ngxSummernote]="config" [ngxSummernoteView]="content"></div> The issue I&apo ...

The Angular SSR feature is throwing errors due to non-ESM modules present in my Express API implementation

In my Angular SSR project, I have set up my Express API to run as part of the SSR service. The app code is located in /src/app, while the API code resides in /src/api. There are some imports of the API code into the app code, primarily for using the same t ...

When communicating with the Rails 5 API, ensure that the post request in Angular 4/Ionic 2 includes the necessary `registration` field

Within my Ionic2/Angular4 application, I have implemented the following method: const body = JSON.stringify(values); let headers = new Headers(); headers.append('Content-Type', 'application/json'); console.log(body) return this.http. ...

What is the process for updating a particular index in a list?

Currently, I am delving into React by working on a task master app. The concept is simple - each user input becomes a new task in an array of tasks. The app features Add, Delete, and Update buttons for managing these tasks. Everything is functioning smoot ...

The URL is not being updated despite changes in document.location hash

I have created a script that toggles (show/hide) between different DIVs on the page (highlighted below in the various boxes =). However, I am facing an issue with updating the URL string when switching between different DIVs. For instance, if I navigate t ...

Angular - Filtering only ag-Grid information

I am currently working on implementing print functionality for ag-Grid in an angular project. I have a page that includes both content and ag-Grid data. When I attempt to use the print functionality, both the content and grid data are being printed. Howeve ...