Angular url matcher - match any path starting with

China☆狼群 提交于 2019-12-10 19:36:54

问题


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
and so on.

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

My router config:

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

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


回答1:


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
 }

you get the captured value in this.url variable.

Its worked perfect. I hope its help.



来源:https://stackoverflow.com/questions/48136986/angular-url-matcher-match-any-path-starting-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!