简体   繁体   中英

Angular 9: queryParams is adding extra characters to the route URL

I have a side navigation bar in my application. All the icons in the side navigation point to different route. One of the icons should point me to a route with a query param. Example- localhost:4200/test?t=1 .

I have an interface for my navigation items that looks like this.

export interface NavigationItem {
  link: string;
  parameters?: string;
  icon: string;
}

I have an array of these Navigation items that I loop over on my side navigation bar. One of the items in the array is this-

{
    link: 'test',
    parameters: '{t:1}',
    icon: 'newIcon',
  }

This is the code snippet in my *ngFor

<a [routerLink]="[item.link]" [queryParams]="item.parameters" routerLinkActive="active" class="navigation-item">
  <mat-icon matListIcon class="icon">{{ item.icon }}</mat-icon>
</a>

I was expecting the route localhost:4200/test?t=1 to open on the icon click. But the route that's being formed is localhost:4200/test?0=%7B&1=t&2=:&3=1&4=%7D

Can you tell me what's going wrong?

It's because your parameters field on NavigationItem is a string so Angular is URL encoding it.

You can either convert parameters to be of type Params (which I strongly recommend) or convert the string to an object using JSON.parse(item.parameters)

Your object should look like:

export interface NavigationItem {
  link: string;
  parameters?: Params;
  icon: string;
}

And you can create it as:

const item = {
  link: 'test',
  parameters: {
    t: 1
  },
  icon: 'newIcon',
} as NavigationItem

The parameters should be of type Params , otherwise it encodes the string you pass in to be usable as a URL

export interface NavigationItem {
  link: string;
  parameters?: Params;
  icon: string;
}

const item = {
  link: 'test',
  parameters: { t: 1 },
  icon: 'newIcon',
}

All you need to assign type Params to your parameters in interface

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

export interface NavigationItem {
  link: string;
   parameters?: Params;
   icon: string;
}

Angular now consider parameters as router params hence avoid encoding it.

Hope this works.

The right way to provide the parameters is using a Params type because of the queryParams doesn't accept a string value. Check your example with the solution from here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM