Search code examples
javascriptangulartypescriptangular6angular-services

Get the url change in angular


I have two different projects.

Authentication Project: has host as http://localhost:4200 Here i will have a login page where user will enter the details for sign in.

After successful login the user will be directed to another Project called Application.

Application Project: has host as http://localhost:8000

So if the user was logged in successful he will be here in dashboard like http://localhost:8000/dashboard page at this application project.

As of this scenario everything is ok.

Suppose if the user was entering into http://localhost:8000/dashboard directly then i need him to redirect to http://localhost:4200 for sign in.

Because without sign in, user cannot go to this project http://localhost:8000/dashboard directly. Auth guard related things were made and everything was working properly.

The thing i am in need is if user gives the url as http://localhost:8000/users (note url is users) directly then he will be coming to sign in page and after sign in i need to redirect to same url where he came from.

SO the scenario is user entering the url manually as http://localhost:8000/users but he is not logged in and so he was redirected to login then after successful login he was redirected to http://localhost:8000/ but i need to redirect him to http://localhost:8000/users because that is the place where he came from.

How to get the url where he came from?

I am using angular 7 applications.


Solution

  • Add the origin url as GET parameter to the redirect from localhost:8000/users to localhost:4200. Something like localhost:4200?url=%2Fusers

    On the login page you check if the parameter is set. If it is set you redirect to localhost:8000/users else you redirect to default localhost:8000/dashboard

    This example shows how to redirect

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

    Remember to use decodeURIComponent to decode the url.

    You can read query parameters with

    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