Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

418
Visualizações
Angular2: Make route paths case insensitive

I have the following routing configuration.

@RouteConfig([
    {
        path: '/home',
        name: 'Homepage',
        component: HomepageComponent,
        useAsDefault: true
    }
)
export class AppComponent {
}

whenever the browser is pointed to /home this route works but not for /Home or any other case variations. How can I make the router to route to the component without caring the case.

thanks

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Here's what I did.

import { DefaultUrlSerializer, UrlTree } from '@angular/router';

export class LowerCaseUrlSerializer extends DefaultUrlSerializer {
    parse(url: string): UrlTree {
        // Optional Step: Do some stuff with the url if needed.

        // If you lower it in the optional step 
        // you don't need to use "toLowerCase" 
        // when you pass it down to the next function
        return super.parse(url.toLowerCase()); 
    }
}

And

@NgModule({
    imports: [
      ...
    ],
    declarations: [AppComponent],
    providers: [
        {
            provide: UrlSerializer,
            useClass: LowerCaseUrlSerializer
        }
    ],
    bootstrap: [AppComponent]
})
over 4 years ago · Santiago Trujillo Relatório

0

A little fix to Timothy's answer, which doesn't change the case of matched parameter names and values:

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

export function caseInsensitiveMatcher(url: string) {
  return function(
    segments: UrlSegment[],
    segmentGroup: UrlSegmentGroup,
    route: Route
  ) {
    const matchSegments = url.split('/');
    if (
      matchSegments.length > segments.length ||
      (matchSegments.length !== segments.length && route.pathMatch === 'full')
    ) {
      return null;
    }

    const consumed: UrlSegment[] = [];
    const posParams: {[name: string]: UrlSegment} = {};
    for (let index = 0; index < matchSegments.length; ++index) {
      const segment = segments[index].toString().toLowerCase();
      const matchSegment = matchSegments[index];

      if (matchSegment.startsWith(':')) {
        posParams[matchSegment.slice(1)] = segments[index];
        consumed.push(segments[index]);
      } else if (segment.toLowerCase() === matchSegment.toLowerCase()) {
        consumed.push(segments[index]);
      } else {
        return null;
      }
    }

    return { consumed, posParams };
  };
}

Edit: beside the problem explained above, there is another subtle bug which is resolved now. The for loop should iterate over matchSegments instead of segments.

over 4 years ago · Santiago Trujillo Relatório

0

update

This didn't make it into the new router yet

original

Regex matchers were introduced recently. This might help for your use case.

See https://github.com/angular/angular/pull/7332/files

And this Plunker from Brandon Roberts

@RouteConfig([
  { name : 'Test',
    //path : '/test',
    regex: '^(.+)/(.+)$', 
    serializer: (params) => new GeneratedUrl(`/${params.a}/${params.b}`, {c: params.c}),
    component: Test
//   useAsDefault: true
  }
])
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda