【问题标题】:Add wildcard to the end of a URL after a specific word在特定单词后的 URL 末尾添加通配符
【发布时间】:2019-04-04 09:15:13
【问题描述】:

我有一个如下所示的网址:

https://localhost:8080/user/login

但是,可以手动附加查询参数,使 URL 看起来像这样。

https://localhost:8080/user/login?ten=123456

所以我需要一个通配符,在“登录”一词之后使用该通配符。

我的 URL 是在一个常量对象中定义的,如下所示:

export const Constants = {
    routing: {
      home: '/',
      userLogin: '/user/login',
}

..and 是这样使用的:

const routing = Constants.routing;
const url = this.routing.userLogin

【问题讨论】:

    标签: regex angular url url-routing wildcard


    【解决方案1】:

    在您的组件中使用Router.navigate 导航到您的网址

    import { Router } from "@angular/router"
    
    constructor(private router : Router){} 
    
    navigateToUserLogin(){
         this.router.navigate([url], { queryParams: { ten: 123456 } });
    }
    

    您可以在用户登录组件中使用ActivatedRoute 来提取url的查询参数

    import { ActivatedRoute } from '@angular/router';
    
    constructor(private route: ActivatedRoute) { }
    
    ngOnInit(){
       this.route.queryParams.subscribe(params=> { console.log(params); });
    }
    

    【讨论】:

    • 我已经使用了路由器,并进行以下比较以查看用户当前是否在登录屏幕上:this.router.url === this.routing.userLogin。现在是用户可以手动将租户作为查询参数附加到 URL 的情况。因此,还应考虑这些手动添加的参数,并评估 URL,就好像查询参数不存在一样。所以我上面的比较应该是这样的:this.router.url === this.routing.userLogin || this.router.url === this.routing.userLoginWithTenant
    【解决方案2】:

    如果我不明白你的问题,我现在不知道吗?

    在“登录”一词之后提取所有内容的正则表达式是:

    (?<=login).*$
    

    如何在组件中申请:

      public ngOnInit(): void {
        let regex = new RegExp("(?<=login).*$");
        const matches = regex.exec(window.location.href);
        if(matches.length>0){
          this.href=matches[0];
        }
      }
    

    对于带有角度查询参数的路由,您可以使用带有 queryParams 属性的 NavigationExtras:

    router.navigate(["user", "login"], { queryParams: { ten: "123456" } });
    

    并使用路由器链接

    <a [routerLink]="["user", "login"]" [queryParams]="{ ten: '123456' }">Login</a>
    

    【讨论】:

    • 我已经使用了路由器,并进行以下比较以查看用户当前是否在登录屏幕上:this.router.url === this.routing.userLogin。现在是用户可以手动将租户作为查询参数附加到 URL 的情况。因此,还应考虑这些手动添加的参数,并评估 URL,就好像查询参数不存在一样。所以我上面的比较应该是这样的:this.router.url === this.routing.userLogin || this.router.url === this.routing.userLoginWithTenant
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    • 2023-01-09
    • 2020-11-04
    • 1970-01-01
    • 2022-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多