Alkis Mavridis
Alkis Mavridis

Reputation: 1211

Angular 7: unwanted redirect when query parameters are present

I use @angular/router with angular 7.

My goal is to use an arbitrary number of (optional) query parameters on one of my pages, in particular in /pages/components

The problem I face is that whenever I enter some query parameters in my URL bar, I get redirected to a weird location. This redirect happens for all my pages, if any query parameter is present.

Example:

I am struggling to make sense out of this redirection.

It looks like the first query parameter has its first 3 letters cut off, the rest of the query string is escaped, and for some reason I always end up in /pages/components/something, even if the url that I typed was a totally different page (maybe because components-page is my only page with a parameter on the RouterModule?).

Here is my routing module:

const appRoutes: Routes = [
  {path: '', component: LoginPageComponent, runGuardsAndResolvers:'always', pathMatch: 'full'},
  {path: 'pages/components', component: ComponentsPageComponent, runGuardsAndResolvers: 'always'},
  {path: 'pages/classes', component: ClassesPageComponent, runGuardsAndResolvers: 'always'},
  {path: 'pages/components/:id', component: ComponentsPageComponent, runGuardsAndResolvers: 'always'},
  {path: 'pages/dashboard', component: DashboardPageComponent, runGuardsAndResolvers: 'always'},
  {path: 'pages/users', component: UserAdminisitrationComponent, runGuardsAndResolvers: 'always', canActivate: [UserRoleGuardService]},
  {path: 'pages/reports', component: ReportsPageComponent, runGuardsAndResolvers: 'always'},
  {path: 'pages/jobs', component: JobsPageComponent, runGuardsAndResolvers: 'always'},
  {path: 'pages/material', component: MaterialPageComponent, runGuardsAndResolvers: 'always', canActivate: [UserRoleGuardService]},
  {path: '**', redirectTo: '/pages/dashboard', pathMatch: 'full'}
];

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

Upvotes: 5

Views: 2422

Answers (1)

Mouadh
Mouadh

Reputation: 299

I had the same problem with Angular 8,

i was doing that :

this.returnUrl = this.route.snapshot.queryParams['returnUrl']
....
this.router.navigate([this.returnUrl]);

when this.returnUrl = "/my-componenet?x=4"; for example i was redirected to "/my-componenet%3Fx%3D4" instead.

the fix was to use navigateByUrl instead

i also added a decodeURI (just in case)

this.returnUrl =decodeURI(this.route.snapshot.queryParams['returnUrl'] || '/login')
    ....
    this.router.navigateByUrl(this.returnUrl);

Upvotes: 1

Related Questions