skip to Main Content

I’m updating an old website with Angular2, and one of the prerequisites is that all URLs must still match.

It’s the very beginning of the development and I’m working on the router.

So far, I have to create a homePage, a productPage and an errorPage.

The “old” links for a product page are like this :
/category/subcategory/some/eventual/other/things/productName-id.html

I’ve copied Matan Shukry’s Complex Url Matcher, and here’s my current code :

import { ComplexUrlMatcher } from '../../functions/complex.url.matcher';

const appRoutes: Routes = [
    {
        path:      '',
        component: HomepageComponent,
    },
    {
        matcher:   ComplexUrlMatcher('product', /.*/), // very permissive regex here, in order to test
        component: ProductComponent,
    },
    {
        path:      '**',
        component: Error404Component,
    },
];

My current problem is that I can match anything, provided my url does not have any slash.

  • /abcdefg.html works (Loads the ProductComponent)
  • /a/b/c/d/e/f/g.html doesn’t (Loads the Error404Component)
  • /a/bcdefg.html doesn’t neither

How can I make these urls match with their full paths (including all the slashes ?).

2

Answers


  1. Chosen as BEST ANSWER

    I finally found a way, helped by anein's function (Thanks, dude !).

    Matan Shukry's method was unnecessary complex for my needs.

    Here's the gist I made : https://gist.github.com/MarcBrillault/87f8df9610cfa3ed112afc3f8da474e8

    Edit: gist updated.


  2. It is better to go with parameters in angular you can define parameters to the route

    { path: 'hero/:a/:b/:c/:d/:e/:f/:g', component: HeroDetailComponent },
    { path: 'hero/:a/:b/:c/:d/:e/:f', component: HeroDetailComponent },
    { path: 'hero/:a/:b/:c/:d/:e', component: HeroDetailComponent },
    { path: 'hero/:a/:b/:c/:d', component: HeroDetailComponent },
    { path: 'hero/:a/:b/:c', component: HeroDetailComponent },
    { path: 'hero/:a/:b', component: HeroDetailComponent },
    { path: 'hero/:a', component: HeroDetailComponent },
    { path: 'hero', component: HeroDetailComponent },
    

    Then subscribe to paramMap

    HeroDetailComponent 
    
    import { ActivatedRoute } from '@angular/router';
    
    constructor(
        private route: ActivatedRoute
    ) { }
    
    this.route.paramMap.subscribe(params => {
      console.log(params);
    });
    

    you will get all the parameters in the subscription and do you operations

    here id is a parameter. same way you can pass multiple parameters to your route
    to create your route structure

    https://angular.io/guide/router#route-parameters-required-or-optional go this link for more details

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search