我有两个不同的项目。
身份验证项目:的主机为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。
您可以使用以下方式读取查询参数
Angular
this.activatedRoute.queryParams.subscribe(params => { const url = decodeURIComponent(params['url']); console.log(url); });
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]) : "";
VanillaJs
VanillaJs
关于javascript - 获取 url 的 Angular 变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53864878/