Using regex for path value of routes in angular2

2019-02-19 03:54发布

问题:

I want to configure route for my angular2 application. My URL needs to be like this:

http://domain_name/constant_value/variable_value/constant_value

The url can be like following examples:

http://localhost/myhouse/floor1/mirror

http://localhost/myhouse/floor1/room1/mirror

http://localhost/myhouse/floor1/room1/bathroom/mirror

Here the routes /myhouse and /mirror are constant. But the middle part can be anything like /floor1 or /floor2/something/something/....

How can i define a route for that in routing module.

const routes: Routes = [
    {
        path: 'myhouse',
        children: [
            {
                path: ..., //here how do i configure it
                children: [
                    {
                        path: '/mirror',
                        component: MirrorComponent            
                    }
                ]
            }
        ]
    }
];

Here the mirror component must be loaded if the url has /mirror at the end of the url if not login component should be loaded. Mirror will be loaded for the urls shown above. Each mirror component will have different propertise value inside according to the variable part of the url.

For login component url will be like:

http://localhost/myhouse

or

http://localhost/myhouse/floor1

or

http://localhost/myhouse/floor1/bathroom1

I tried wanted to use regex but it seems the regex is not supported for newer version of angular2. If I am wrong on not being able to use regex please kindly point me to that direction with an example. If not please point me to right direction.

回答1:

You could use a UrlMatcher by providing matcher key for a Route. Unfortunately it's undocumented for now, so you may need to check the source of router/src/config.ts:

/**
 * @whatItDoes Represents the results of the URL matching.
 *
 * * `consumed` is an array of the consumed URL segments.
 * * `posParams` is a map of positional parameters.
 *
 * @experimental
 */
export type UrlMatchResult = {
  consumed: UrlSegment[]; posParams?: {[name: string]: UrlSegment};
};

/**
 * @whatItDoes A function matching URLs
 *
 * @description
 *
 * A custom URL matcher can be provided when a combination of `path` and `pathMatch` isn't
 * expressive enough.
 *
 * For instance, the following matcher matches html files.
 *
 * ```
 * function htmlFiles(url: UrlSegment[]) {
 *  return url.length === 1 && url[0].path.endsWith('.html') ? ({consumed: url}) : null;
 * }
 *
 * const routes = [{ matcher: htmlFiles, component: HtmlCmp }];
 * ```
 *
 * @experimental
 */
export type UrlMatcher = (segments: UrlSegment[], group: UrlSegmentGroup, route: Route) =>
UrlMatchResult;

This basically allows you to write a function that can do any kind of matching, including regular expressions.

It's still experimental, so there aren't many examples around, but github/matanshukry has kindly provided a gist example of ComplexUrlMatcher. It should give you an idea how to implement one that suits your needs (sadly there's no license, so you can't use it as-is).



回答2:

Try to do that:

const routes: Routes = [
    {
        path: 'myhouse',
        children: [
            {
                path: ':name', //FOR VARIABLE VALUE
                children: [
                    {
                        path: 'mirror', //REMOVE SLASH
                        component: MirrorComponent            
                    }
                ]
            }
        ]
    }
];

Here you will find a better explanation: http://vsavkin.tumblr.com/post/146722301646/angular-router-empty-paths-componentless-routes



回答3:

Late to answer but If you still have the same issue here's how I solved the same problem..

This is my route

{
    path: 'myhouse',
    component: MyParenthouseComponent,
    children : [{
        path: '**',
        component: MyhouseComponent
    }]
}

I have defined myhouse as parent route and defined a ** child route to it. Parent component MyParenthouseComponent holds a <router-outlet></router-outlet> as template, nothing else.(If you need anything else it's upto you)

IN my MyhouseComponent ngOnInit I am doing simply this

_router.events.subscribe((val) => {
    console.log(val);
    if(val instanceof NavigationEnd) {
        var url = this._router.url;
        //do anything with url
    }
});

imported routes like this

import { Router, ActivatedRoute, ParamMap, NavigationStart, NavigationEnd } from '@angular/router';

This will get me the current route

For example in case of this route

http://localhost/myhouse/floor1/room1/bathroom/mirror

it will give me

/myhouse/floor1/room1/bathroom/mirror

You can easily manipulate this url for your use.



回答4:

Here's how you can solve this.

import { Routes, UrlSegment } from '@angular/router';

const myHouseRouteMatcher =
    (url: UrlSegment[]) => ({ consumed: url.slice(0, -1) });

const routes: Routes = [
    {
        path: 'myhouse',
        children: [
            {
                matcher: myHouseRouteMatcher,
                children: [
                    {
                        path: 'mirror',
                        component: MirrorComponent
                    },
                    {
                        path: 'bathtub',
                        component: BathtubComponent
                    }
                ]
            }
        ]
    }
];