Search code examples
angularangular-routing

Angular matcher children not working


I want to implement some url like "domain/username/timeline". The username is "string.string" so I used UrlSegment to match the string using regx. Now when I navigate to "domain/username", its working but when I navigate to "domain/username/settings" it doe not work at all.

Any help is welcome. If there is any similar approach I welcome it.

Here is my app-routing module

import { NgModule } from '@angular/core';
import { RouterModule, Routes, UrlSegment, UrlMatcher, UrlMatchResult } from '@angular/router';
import { TimelineComponent } from './components/profile/timeline/timeline.component';
import { AboutComponent } from './components/profile/about/about.component';
import { FollowersComponent } from './components/profile/followers/followers.component';

export function userMatch (url: UrlSegment[]): UrlMatchResult{
    if (url.length === 1) {
        if (url[0].path.match(/^[a-z]*\.[a-z0-9_]*$/)) {
            return ({
                    consumed: url
            });
        } else {
            return null;
        }
    } else if(url.length === 2) {
        if (url[0].path.match(/^[a-z]*\.[a-z0-9_]*$/)) {
            return ({
                    consumed: url, 
                    posParams: {timeline: url[1], about: url[1], settings: url[1] }
            });
        } else {
            return null;
        }       
    }
}

const appRoutes: Routes = [
    /**
     * @route `PROFILE` 
     * @lock `CanActivate`
     *  Only if logged in can access this page
     */
    {
        matcher: userMatch, 
        component: ProfileComponent,
        canActivate: [AuthGuard],
        children: [
            { path: '', component: TimelineComponent },
            { path: 'timeline', component: TimelineComponent },
            { path: 'about', component: AboutComponent },
            { path: 'settings', component: SettingsComponent }
        ]
    }
]

@NgModule({
    imports: [
        RouterModule.forRoot(appRoutes)
    ],
    exports: [
        RouterModule
    ]
})export class AppRoutingModule { }

Solution

  • See https://github.com/angular/angular/issues/23866. You should return in the consumed parameter used segments of url.

    For example, if you want to match the first and the second segments of the url /categories/categoryId/products (which are /categories/categoryId). The matcher function would look like this:

    export function categoryMatcher(url: UrlSegment[]) {
      return url.length === 3 ? ({consumed: url.slice(0,2)}) : null;
    }