javascript - 获取 url 的 Angular 变化

标签 javascript angular typescript angular6 angular-services

我有两个不同的项目。

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

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

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

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

到目前为止,一切正常。

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

因为没有登录,用户无法进入该项目http://localhost:8000/dashboard直接地。 与身份验证守卫相关的事情已经完成,一切正常。

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

所以场景是用户手动输入 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. 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

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

相关文章:

javascript - 在 TypeScript 2.0 中正确使用 React.Events?

javascript - Kineticjs 类层次结构说明

javascript - 如何显示我的 html 文件,它是 JSF 中的字符串格式?

javascript - HTML 如何填充内容

javascript - 无法读取未定义的属性 'propostas_realizadas' - Angular 2

javascript - 有没有办法在 Angular 渲染到屏幕之前打印组件原始代码?

javascript - 指令仅被调用一次

javascript - 从 url 中提取 img - 脚本在 jsfiddle 中有效,但在我的网站上无效,有人能找出原因吗?

angular - 使用 *ngFor 遍历数组并使用 *ngIf 从数组中选择要列出的元素

javascript - While 循环中的 Angular 5 更新 View