代码之家  ›  专栏  ›  技术社区  ›  Maniraj Murugan

获取url的角度更改

  •  2
  • Maniraj Murugan  · 技术社区  · 7 年前

    二 不同的项目。

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

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

    应用项目: 作为主人 http://localhost:8000

    因此,如果用户成功登录,他将出现在仪表板中 http://localhost:8000/dashboard

    在这种情况下,一切都正常。

    认为 http://localhost:8000/dashboard 然后我需要他直接转到 http://localhost:4200 用于登录。

    因为没有登录,用户无法转到此项目 直接地 与Auth-guard相关的东西都做好了,一切正常。

    我需要的东西 http://localhost:8000/users (注意url是 使用者 )然后他将直接进入登录页面,登录后我需要重定向到 相同的url 他来自哪里。

    http://localhost:8000/users http://localhost:8000/ 但是 我需要 把他转到 http://localhost:8000/users 因为那是他来的地方。

    如何获取他来自的url?

    4 回复  |  直到 7 年前
        1
  •  2
  •   Thomas Sablik    7 年前

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

    在登录页面上,检查参数是否已设置。如果设置为,则重定向到localhost:8000/用户,否则重定向到默认localhost:8000/仪表板

    此示例演示如何重定向

    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. 有棱角的

      this.activatedRoute.queryParams.subscribe(params => {
          const url = decodeURIComponent(params['url']);
          console.log(url);
      });
      
    2. 瓦尼拉伊斯

      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. 瓦尼拉伊斯

      URLSearchParams

    4. 瓦尼拉伊斯

      Url.searchParams

        2
  •  1
  •   Akshay Rajput    7 年前

    在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,否则重定向到默认页面。希望这有帮助

        3
  •  0
  •   Abdelrahman Ayyad    7 年前

    您可以创建一个角度服务,例如重定向服务,它有一个布尔标志 和重定向url 当用户输入url时 在ngOnInit方法中,您将标志设置为true,并使用路由器模块获取url

        4
  •  0
  •   jazza1000    7 年前

    我们就是这样做的:

     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

    推荐文章