Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

587
Views
Angular 2 Cómo redirigir a 404 u otra ruta si la ruta no existe

Estaba tratando de redirigir 404 / otra ruta si la ruta no existe en angular 2

Intenté investigar que hay algún método para angular 1 pero no para angular 2.

Aquí está mi código:

 @RouteConfig([ { path: '/news', name: 'HackerList', component: HackerListComponent, useAsDefault: true }, { path: '/news/page/:page', name: 'TopStoriesPage', component: HackerListComponent }, { path: '/comments/:id', name: 'CommentPage', component: HackerCommentComponent } ])

Entonces, por ejemplo, si redirijo a /news/page/ , entonces funciona y me devuelve una página vacía, ¿cómo maneja este tipo de caso?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Para la versión v2.2.2 y posteriores

En la versión v2.2.2 y posteriores, la propiedad de nombre ya no existe y no debe usarse para definir la ruta. se debe usar la ruta en lugar del nombre y no se necesita una barra inclinada inicial en la ruta. En este caso, use path: '404' en lugar de la path: '/404' :

 {path: '404', component: NotFoundComponent}, {path: '**', redirectTo: '/404'}

Para versiones anteriores a v2.2.2

puede usar {path: '/*path', redirectTo: ['redirectPathName']} :

 {path: '/home/...', name: 'Home', component: HomeComponent} {path: '/', redirectTo: ['Home']}, {path: '/user/...', name: 'User', component: UserComponent}, {path: '/404', name: 'NotFound', component: NotFoundComponent}, {path: '/*path', redirectTo: ['NotFound']}

si ninguna ruta coincide, redirija a la ruta NotFound

over 4 years ago · Santiago Trujillo Report

0

A medida que Angular avanzaba con el lanzamiento, enfrenté este mismo problema. Según la versión 2.1.0 , la interfaz Route se ve así:

 export interface Route { path?: string; pathMatch?: string; component?: Type<any>; redirectTo?: string; outlet?: string; canActivate?: any[]; canActivateChild?: any[]; canDeactivate?: any[]; canLoad?: any[]; data?: Data; resolve?: ResolveData; children?: Route[]; loadChildren?: LoadChildren; }

Entonces mis soluciones fueron las siguientes:

 const routes: Routes = [ { path: '', component: HomeComponent }, { path: '404', component: NotFoundComponent }, { path: '**', redirectTo: '404' } ];
over 4 years ago · Santiago Trujillo Report

0

Mi opción preferida en 2.0.0 y posteriores es crear una ruta 404 y también permitir que una ruta de ruta ** se resuelva en el mismo componente. Esto le permite registrar y mostrar más información sobre la ruta no válida en lugar de una simple redirección que puede actuar para ocultar el error.

Ejemplo sencillo de 404:

 { path '/', component: HomeComponent }, // All your other routes should come first { path: '404', component: NotFoundComponent }, { path: '**', component: NotFoundComponent }

Para mostrar la información de ruta incorrecta, agregue la importación al enrutador dentro de NotFoundComponent:

import { Router } from '@angular/router';

Agréguelo a la construcción de NotFoundComponent:

constructor(public router: Router) { }

Entonces estará listo para hacer referencia a él desde su plantilla HTML, por ejemplo

The page <span style="font-style: italic">{{router.url}}</span> was not found.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!