【问题标题】:Angular url matcher - match any path starting withAngular url matcher - 匹配任何以开头的路径
【发布时间】:2018-01-07 12:17:09
【问题描述】:

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

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

我尝试了这种方法,但它不起作用:https://github.com/angular-ui/ui-router/wiki/URL-Routing#regex-parameters

我的路由器配置:

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

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

【问题讨论】:

  • 为什么在使用另一个完全不同的路由器时要查找 angular-ui-router 的文档:原生 Angular 路由器?这是您需要使用的:angular.io/api/router/Route#matcher
  • 我知道这一点,但是本文档中没有任何有用的信息可以回答我的问题。所以我想URL匹配可能是一样的,试了一下。
  • 有。我链接到它。它甚至包含一个示例。

标签: angular angular-ui-router


【解决方案1】:

这是解决方案试试这个..

    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);
            }
          }
        );

      }
    }

你可以在这里改变你的匹配部分

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

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

它运行完美。我希望它的帮助。

【讨论】:

    猜你喜欢
    • 2016-09-12
    • 2017-09-27
    • 2016-07-23
    • 2019-12-25
    • 1970-01-01
    • 1970-01-01
    • 2019-01-19
    • 1970-01-01
    • 2016-09-16
    相关资源
    最近更新 更多