Discover how to modify the URL in Angular

There are two distinct projects under consideration.

Authentication Project: is hosted at http://localhost:4200. This project contains a login page where users can input their credentials to sign in.

Upon successful login, the user will be redirected to another project called Application.

Application Project: is hosted at http://localhost:8000

If the user has logged in successfully, they will arrive at the dashboard located at http://localhost:8000/dashboard within this application project.

So far, everything seems to be functioning correctly.

In the event that a user attempts to access http://localhost:8000/dashboard directly, I want them to be redirected to http://localhost:4200 for signing in.

Since access to this project http://localhost:8000/dashboard is restricted without signing in. Auth guard measures have been implemented and are working properly.

What I require is if a user inputs the URL as http://localhost:8000/users (note the URL contains users) directly, then they should be directed to the sign-in page. Upon successful sign-in, they should be redirected to the same URL from which they initially accessed.

Therefore, the scenario involves a user manually entering the URL as http://localhost:8000/users, being met with the sign-in page due to not being logged in, and upon successful sign-in, being redirected to http://localhost:8000/. However, I need to redirect them to http://localhost:8000/users instead, as that was their original location.

How can I retrieve the URL from which the user came?

My applications are built using Angular 7.

Answer №1

To set the origin URL as a GET parameter for the redirect from localhost:8000/users to localhost:4200, you can do something like localhost:4200?url=%2Fusers

When on the login page, check if the parameter is set. If it is, redirect to localhost:8000/users; otherwise, redirect to default localhost:8000/dashboard.

This serves as an example of how to perform a redirect.

let currentUrl;
// get current url, e.g. currentUrl = "/users"
// or currentUrl = window.location.pathname
window.location.href = "http://localhost:4200?url=" + encodeURIComponent(currentUrl);

Don't forget to use decodeURIComponent to decode the URL.

You can access query parameters using:

  1. Angular

    this.activatedRoute.queryParams.subscribe(params => {
        const url = decodeURIComponent(params['url']);
        console.log(url);
    });
    
  2. VanillaJs

    let urlParam = window.location.search.substr(1).split("&").map(function(el) {return el.split("=");}).find(function(el) {return el[0] === "url";})
    let url = urlParam ? decodeURIComponent(urlParam[1]) : "";
    
  3. VanillaJs

    URLSearchParams

  4. VanillaJs

    Url.searchParams

Answer №2

Within your Authentication Guard, you have the option to store the previous URL visited by the user. If the user is not logged in, they will be redirected to the login page. After successful login, the system will check if there was a previously set redirect URL in the service. If one exists, the user will be redirected to that page; otherwise, they will be directed to the default page.

canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
): boolean {
    const url: string = state.url;
    if (this.loginService.isUserLoggedIn()) {
        return true;
    }
    this.loginService.setRedirectUrl(url);
    this.loginService.redirectToLogin();
    return false;
}

In the loginService.ts file:

setRedirectUrl(url: string): void {
    localStorage.setItem('state', url);
}

After logging in, the system will verify if there is a stored state key in the local storage. If found, the user will be redirected to that URL; otherwise, they will be sent to the default page. We hope this explanation aids in understanding the process.

Answer №3

If you're looking to streamline your Angular application, consider implementing a redirect service with a boolean flag and designated redirect URL. Upon user inputting an URL, initialize the flag in the ngOnInit method then use the router module to capture the URL. When navigating to the login page, check the flag status and trigger redirection post-login.

Answer №4

Here's a glimpse of our process:

Starting with the AuthGuard

 canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

if (this.isAuthorized) {
  return true;
}

// If not logged in, redirect to login page with return url
console.log("Redirecting to login page with return url: "+ state.url);
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
return false;
  }

Subsequently, during the login process, we guide them back to the returnUrl

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

Jquery: Pressing Enter will cause the input field to lose

Take a look at this fiddle I created: http://jsfiddle.net/7wp9rs2s/. This is the progress I have made on my project so far. In the fiddle above, you can double click on one of the 4 items and a textbox will appear for editing. Instead of clicking out of t ...

What could be causing my application to hang on my local server?

Recently, I developed a NodeJS and Express MVC (or perhaps more accurately VC) app. Initially, everything worked smoothly until I integrated express-validator and included the middleware in the app file. This caused my localhost to freeze, displaying a GET ...

The element 'mat-form-field' is unrecognized in Angular 9 and Material 9.2.0 version

Greetings! I am currently utilizing Angular 9 and here is the code snippet I am working with: The HTML component named "post-create.component.html": <mat-mat-form-field> <textarea rows="6" [(ngModel)]="enteredValue"></textarea> </ma ...

What is preventing this JSON object from being parsed correctly?

Within my JavaScript file, The process of declaring and parsing the ajax response text is as follows: var subcats = JSON.parse(this.responseText); The actual responseText that needs to be parsed looks like this: {"presubcatId":"1","precatId":"1","presu ...

Tips for implementing a filtering function within an array of objects

I am struggling to implement a filter search feature in my ionic mobile application for an array of objects. The array is structured like this: initializeItems() { this.items = [ {Place:"Dumaguete city", date:"February 2 2018"}, {Place:"Sibulan", date: ...

Tips for crafting effective error messages to communicate with users

One of the biggest challenges I face is crafting clear error messages for clients in case of errors. A typical scenario involves using Axios and a third-party API to fetch data, requiring appropriate error handling for both. Axios' error handling doc ...

Update the multidimensional array function to ES6 syntax

I'm in the process of developing a function for my app and I'm curious if there's a more elegant way to implement it using ES6, without relying on two for loops. The goal is to create a multi-dimensional array that keeps track of x and y co ...

When redirecting to the same component, Vue.js hooks are not triggered

In my Vuejs project, I have two pages located at the same level with a common component. However, when I redirect from post/new to post/edit/:id, the beforeMount method is not being called. redirect() { this.$router.push({path: `home/post/edit/${this ...

Unable to resize images in Firefox

Why is it that resizing doesn't seem to work in Firefox but functions fine in Internet Explorer? I'm struggling to find a way to make it consistent across all browsers. My goal is to resize the width to 800 and height to 475, disable maximizing t ...

Leveraging spread syntax and styling for array string interpolation in JavaScript

Imagine I have an array such as [1,2,3] and my goal is to insert its values into a string format like: the values are (?, ?, ?) Can anyone suggest a simple solution for this? I am aware of the spread operator ...[1,2,3], and it's feasible to conver ...

Acquire feedback from PHP using SweetAlert notifications

I need to update my HTML form to function like this: <script> function getName() { var name = $('#name').val(); var url_send = 'send.php'; $.ajax({ url: url_send, data: 'name=' + name, ...

Having trouble getting the if statement to run with JavaScript Closures?

Check out this code snippet: let url = URL; let imageURL = ''; $.getJSON("https://graph.facebook.com/?id="+encodeURIComponent(url)+"&scrape=true&method=post", function (data) { let json_data = JSON.stringify(data); json_data ...

What could be causing the directives module to not get properly incorporated into the Angular app module?

I am currently in the process of learning Angular and have come across some challenges with module resolution. In js/directives/directives.js, I have a directive scoped within a directives module: angular.module("directives").directive("selectList", funct ...

Creating artistic designs on an item with Three.js

My goal is to use the mouse to paint on the surface of objects. For inspiration, check out this example: Can anyone provide a basic example of how to achieve this? I believe the process involves painting on a canvas and then applying it to the 3D object ...

A step-by-step guide on initializing and setting a cookie value with expiration

Below is the code I have added. Can someone please help me locate the bug? Here is the code snippet: $_SESSION['browser'] = session_id(); setcookie($expire, $_SESSION['browser'], time() + (60 * 1000), "/"); echo "Value is: " . $_COO ...

How can I incorporate shared Angular 2 components in my Angular 2 web application with the help of webpack?

I've been attempting to incorporate shared angular-2 components into another angular-2 web project by duplicating them in the node_modules folder. Unfortunately, this method has not proven successful. You can access the entire project at Ng2-Webpack- ...

Can an XSS attack occur on a style tag with inline styling?

For example: <!DOCTYPE html> <html lang="en"> <head> <title>Test for Potential XSS Attack</title> <style> div { background-color:blue; height:120px; ...

Tips for styling dates in an Angular Material table

My web API provides me with this data: https://i.sstatic.net/9pGuO.png The data is in the form of an array of IOferta export interface IOferta { id: string idPresentada: string; descripcion: string; fechaPresentacion: Date; responsable: string; pre ...

Conceal multiple divs at the same time based on their largest dimension

I am facing an issue with two divs, each containing two nested divs: https://i.sstatic.net/QFMiU.png <div class="hide"> <div> Variable size </div> <div> Text1 (also variable size) </div&g ...

If I remove my project but still have it saved on my GitHub, do I need to reinstall all the dependencies or can I simply run npm install again?

I have a question regarding my deleted project that is saved on GitHub. If I formatted my PC and lost the project but it's still on GitHub, do I need to reinstall all the dependencies or can I just run 'npm install'? The project has dependen ...