在 angular 中获取 url 的变化

Get the url change in angular

我有两个个不同的项目。

身份验证项目: 主机为 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

所以情况是用户以 http://localhost:8000/users 手动输入 url 但他没有登录,因此他被重定向到登录,然后在成功登录后他被重定向到 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

在您的 Auth Guard 中您可以保存之前的 URL;如果 cx 未登录,则将 cx 重定向到登录页面。用户成功登录后,检查服务中是否有任何 setRedirect URL,如果是,则重定向到该页面,否则重定向到默认页面。

canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
): boolean {
    const url: string = state.url;
    if (this.loginService.isUserLoggedIn()) {
        return true;
    }
    this.loginService.setRedirectUrl(url);
    this.loginService.redirectToLogin();
    return false;
}

loginService.ts

setRedirectUrl(url: string): void {
    localStorage.setItem('state', url);
}

一旦用户登录,检查本地存储中是否有任何状态密钥,如果是,则重定向到那个 URL,否则重定向到默认页面。希望这有帮助

您可以创建一个 angular 服务,例如重定向服务,它有一个布尔标志 并重定向 url 当用户输入 url 在 ngOnInit 方法中,您将标志设置为 true 并使用路由器模块获取 url 并在登录页面上检查标志并在登录后重定向

这就是我们所做的:

在 AuthGuard

 canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

if (this.isAuthorized) {
  return true;
}

// not logged in so redirect to login page with the return url
console.log("navigating to login page with return url: "+ state.url);
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
return false;
  }

然后在登录中我们将它们重定向回 returnUrl