Home > Blockchain >  Angular query param with parenthesis?
Angular query param with parenthesis?

Time:10-21

I have a simple Angular app that uses a query param from the router as follows:

const routes: Routes = [{
  path: '',
  component: DefaultComponent
},
{
  path: ':uname',
  component: ProductDisplayComponent
}];

This works great and I can access the 'product' "uname" as follows:

let prodId = params.get('uname')

The issue is that some of the "uname" values are numbers and some are numbers with brackets, for example "567(B)"

Everything works fine if the "uname" is just a number, but once the parenthesis are in the uname the app just redirects to "/".

Is there anyway to get the value when the "unmae" has parenthesis?

Thank you,

CodePudding user response:

Because parentheses have a special meaning, I've done a little bit of extra processing, but I'll give you a little example that HOPEFULLY makes sense

   {
      path: 'd', component: DComponent,
      children:[
        {path: 'c', component: CComponent},
        {path: 'a', component: AComponent,outlet:'right'},

      ]
    },
    this.router.navigateByUrl('/home/d/(c//right:a)')

It is mainly used as a secondary route outlet

CodePudding user response:

Based on the following report: github.com/angular/angular/issues/10280, this is how I solved my issue as originally posted.

  1. Create a new class as follows:

    import { UrlSerializer, UrlTree, UrlSegment, DefaultUrlSerializer } from '@angular/router';
    
     export class CustomUrlSerializer implements UrlSerializer {
    
         private dus = new DefaultUrlSerializer();
    
       parse(url: any): UrlTree {
            url = url.replace(/\(/g, '(').replace(/\)/g, ')');
            return this.dus.parse(url)
       }
    
       serialize(tree: UrlTree): any {
         return this.dus.serialize(tree).replace(/(/g, '(').replace(/)/g, ')');
       }
     }
    
  2. in "app.modules.ts" (or whatever you modules file is) add the following to providers:

     providers: [MyOtherServices,  { provide: UrlSerializer, useClass: CustomUrlSerializer }],
    

    more...

Good luck

  • Related