gpt4 book ai didi

javascript - 获取 Angular url变化

转载 作者:搜寻专家 更新时间:2023-10-30 21:26:42 27 4
gpt4 key购买 nike

我有两个不同的项目。

身份验证项目: 主机为 http://localhost:4200在这里我将有一个登录页面,用户将在其中输入详细信息以进行登录。

成功登录后,用户将被定向到另一个名为 Application 的项目。

应用程序项目: 主机为 http://localhost:8000

因此,如果用户成功登录,他将在该应用程序项目的仪表板中,如 http://localhost:8000/dashboard 页面。

在这种情况下一切正常。

假设 如果用户直接进入http://localhost:8000/dashboard 那么我需要他重定向到http://localhost: 4200 用于登录。

因为没有登录,用户不能直接进入这个项目http://localhost:8000/dashboard。与 Auth Guard 相关的东西已经制作完成,一切正常。

我需要的是 如果用户将 url 指定为 http://localhost:8000/users(注意 url 是 users) 然后他会直接来登录页面,登录后我需要重定向到他来自的相同的 url

所以场景是用户手动输入 url 作为 http://localhost:8000/users 但是他没有登录所以他被重定向到登录然后在成功登录后他被重定向到http://localhost:8000/我需要 将他重定向到 http://localhost:8000/users 因为那是地方他来自哪里。

如何获取他来自哪里的url?

我正在使用 Angular 7 应用程序。

最佳答案

将源 url 作为 GET 参数添加到从 localhost:8000/users 到 localhost:4200 的重定向。类似于 localhost:4200?url=%2Fusers

在登录页面上检查是否设置了参数。如果它被设置你重定向到 localhost:8000/users 否则你重定向到默认的 localhost:8000/dashboard

这个例子展示了如何重定向

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

记得使用decodeURIComponent来解码url。

你可以读取查询参数

  1. Angular

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

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

    URLSearchParams

  4. Vanilla

    Url.searchParams

关于javascript - 获取 Angular url变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53864878/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com