角度网址匹配器-匹配以开头的任何路径 [英] Angular url matcher - match any path starting with

查看:107
本文介绍了角度网址匹配器-匹配以开头的任何路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用angular2 +路由器,并且尝试匹配以/tree开头的任何路径,例如:

I use angular2+ router and I'm trying to match any path starting with /tree e.g:

example.com/projects/1/repository/tree/src
example.com/projects/1/repository/tree/src/app
example.com/projects/1/repository/tree/src/app/core
等等.

example.com/projects/1/repository/tree/src
example.com/projects/1/repository/tree/src/app
example.com/projects/1/repository/tree/src/app/core
and so on.

我尝试了这种方法,但是不起作用:

I tried this approach, but it doesn't work: https://github.com/angular-ui/ui-router/wiki/URL-Routing#regex-parameters

我的路由器配置:

const routes: Routes = [
{
    path: 'projects/:id/repository/{tree:.*}',
    component: FilesListComponent
}

tree之后的所有内容都需要在控制器中捕获为参数,因此可以使用它进行API调用.

Everything after tree I need to capture as a parameter in the controller, so I can make an API call with it.

推荐答案

下面是解决方案,尝试一下.

Here is the solution try this..

    import { Component } from '@angular/core';
    import { Router } from "@angular/router";
    import { Event as NavigationEvent } from "@angular/router";

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      public url: string;
      constructor(router: Router) {

        router.events.subscribe((event: NavigationEvent): void => {
            this.url = router.url;
            if (this.url.match('/tree/')) {          
              console.log("Matched your Path",this.url);
            }
          }
        );

      }
    }

您可以在此处更改匹配的部分

you can change your matching part is here

 if(this.url.match('give your matching here')){
       //do something
 }

您可以在this.url变量中获取捕获的值.

you get the captured value in this.url variable.

它的工作非常完美.希望能对您有所帮助.

Its worked perfect. I hope its help.

这篇关于角度网址匹配器-匹配以开头的任何路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆