Redirecting in AngularJS after a successful login操作

Is there a way to redirect users back to the original page after they login? For example, if a user is on a post like www.example.com/post/435 and needs to log in to "like/comment" on the post, how can I automatically redirect them back to that specific post after successful login?

$http.post('/sessionHandler/login', $scope.form).
      success(function(data){
        history.back(); // This approach may not work as expected, especially if the user's previous path was on another site or a new tab in the browser.
      }).error(function(err){
        $scope.errorMessage = err;
      });

I've also come across examples using $locationChangeStart, but I'm having trouble understanding how it works. Here's what I have so far:

$http.post('/sessionHandler/login', $scope.form).
      success(function(data){
   $rootScope.$on("$locationChangeStart", function (event, next, current) {
      $location.path();// How can I access the previous URL where the user came from?
                       // How do I use event, next, and current to determine the last path within my site, 
                      // and ensure it's not an external website?  
    });

      })

Any help would be greatly appreciated!

Answer №1

While it may not be the most optimal solution, I have found success using a cookie to handle redirection to new locations. Whenever I need to redirect, I set the cookie with

$cookies.loginDestination = $location.path()
. Then, when a user logs in, I retrieve and clear the cookie like so:

var loginDestination = $cookies.loginDestination || '/';
$cookies.loginDestination = null;
$location.path(loginDestination);

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 is not able to render Hindi content properly

I am attempting to showcase some Hindi words using JQuery because these are essential contents that need to be displayed on every page of the website. Please note that this is a static website built with HTML and JQuery/JavaScript. Below is my JS file: in ...

Having trouble getting the Facebook like button to display on my website using an iframe in the markup

I gave it my all to try and get it to work, but unfortunately, I was unsuccessful. This is the approach I took. First, I followed the instructions provided on https://developers.facebook.com/docs/plugins/like-button. Next, I copied and pasted the iframe ...

Analyzing a text file against a string to identify discrepancies using Node.js

Recently, I came across a dilemma involving a text file containing information on all Wifi connections (such as ssid, mac no, strength, etc.) that were within my laptop's range just 2 minutes ago. Now, I've rerun the code and obtained the current ...

Error 8007 encountered when attempting to scale at 100% proficiency. Transformation unsuccessful

Wondering if this could be a bug in Photoshop. When scaling a layer and entering values of 100%, an error message pops up: var srcDoc = app.activeDocument; var numOfLayers = srcDoc.layers.length; // main loop for (var i = numOfLayers -1; i >= 0 ; i-- ...

Exclude crypto-browserify from the NextJS build process

I have been dedicated to minimizing the build size of my app as much as possible, and I have observed that the crypto-browserify module is consuming a significant amount of space. While I understand that Next.js polyfills the node module if necessary, I wo ...

Develop a Vue component for a fixed sidebar navigation

I am in need of a vertical navigation bar positioned to the left of my app's layout, with the content extending across the right side. However, I am currently facing an issue where the navbar is pushing all the content downwards. How can I resolve thi ...

How can I ensure that the form submit event is delayed until the onChange event is completed when using jQuery?

Imagine a scenario where a textbox on a webpage has a 'change' event attached to it using jQuery. $('.myFormClass').on('change', '.amount', function () { // An AJAX call is made here, and the respons ...

Exploring the functionality of angular reactive forms in creating intricate JSON structures

After numerous attempts to resolve the issue on my own, I am reaching out to an Angular developer for assistance. My goal is to display a JSON object in the UI: Here is the JSON Object : items={"departure":"New York","arrival":"California","stations":[ ...

Deciphering the issue: "Error: ng:areq"

Hello, I have developed a sample program using Ionic framework. In the app.js file of my Ionic project, I defined a variable as follows: (var itemCheck=angular.module('Shop',['ionic','starter.controllers']);) Below is a snipp ...

Troubleshooting why Vue.js isn't updating the DOM with two-way binding

I'm currently utilizing Vue.js for implementing two-way binding. One issue I am facing is with an edit button that should convert a text field into an input field upon clicking. However, the DOM does not update immediately as expected. For instance: ...

Is there a method to establish varied usage permissions for a single page without any tracking?

I am puzzled by how a solution could create something like this. My goal is to have a webpage displaying 2 squares on a large screen. There will be 2 users, each needing access to write in their own square only on this page. <div class="square1"> ...

Tips for incorporating animation when opening a Jquery SimpleModal

The SimpleModal website features an animation-enabled example with the following sequence: 1. Display modal only 2. Fade in the overlay The code snippet for this animation is as follows: $("#the-div").modal({ onOpen: function (dialog) { dialog.overl ...

How to resolve the issue of "Fixing 'Unhandled Runtime Error TypeError: event is undefined'"

Today I encountered this error: Unhandled Runtime Error TypeError: event is undefined and couldn't find a solution online Here's the code snippet: import { ethers } from 'ethers' import { create as ipfsHttpClient } from 'ipfs-h ...

Issue encountered while attempting to retrieve data from a local json file due to Cross-Origin Resource Sharing

I'm attempting to fetch and display the contents of a JSON file on a webpage, but I'm encountering this error message: Access to XMLHttpRequest at 'file:///C:/Users/bobal/Documents/htmlTry/myData.json' from origin 'null' has ...

React.js Filter Component

I'm currently trying to create a filter for my "localtypes", but I'm encountering an issue where the console in my browser is displaying an empty array. My goal is to access the localtypes properties of the API that I am working with. I attempte ...

Issue with package: Unable to locate the module specified as './artifacts/index.win32-ia32-msvc.node'

I am encountering an issue while using Parcel for the first time. When I execute npx parcel .\app\index.html, I receive the following error: Error: Module not found './artifacts/index.win32-ia32-msvc.node' Require stack: - C:\Users ...

What is causing the TouchSwipe jQuery plugin not to function in my code?

I have integrated the TouchSwipe jQuery plugin into my code to detect mouse movement and display the number of pixels moved when swiping left or right. To download the TouchSwipe jQuery plugin, I visited this link: TouchSwipe and then proceeded to use it ...

disabling past dates in Bootstrap calendar

How can I disable past dates in Bootstrap easily? <script type="text/javascript"> $(function(){ $('.datepicker').datepicker(); }); </script> Date: <input type="text" class="datepicker"></input> I have added the ...

Comparing Data Manipulation Techniques: Server Side vs Client Side Approaches in Reddit API Integration

As I delve into creating a simple Node/Express web application that fetches data from the Reddit API, performs some alterations on it, and intends to present this information using Charts.js on the client side, I find myself facing a dilemma due to my limi ...

What is the best way to showcase an array of objects in a table using AngularJS that updates

My technology stack includes angular.js for the front-end, node.js for server-side operations, and PostgreSQL for managing my database. Currently, I have a list of values stored in the database: Upon checking the controller code, I obtained the following ...