Navigating Angular Router with Special Characters in URL and How Browsers Handle Encoding

I'm really struggling to find a solution for this issue. I'm currently working on designing a search engine that displays the user's query in the URL like this:

https://my-site.com/search;query=%28rockstar;search=true;page=0

The user is looking for the phrase (rockstar.

When I enter this URL into the browser, it functions as expected. However, Google Chrome displays the URL differently:

https://my-site.com/search;query=(rockstar;search=true;page=0

So, the %28 gets changed to (. I'm not sure if this behavior is specific to Angular or dependent on the browser. When the URL contains (, hitting F5 for refresh does not work because the Angular Router reports an error like this:

Cannot match any routes. URL Segment: 'rockstar;search=true;page=0'

Copying the link from the address bar is also ineffective due to this conversion issue - the copied link includes the character ( instead of %28. How can I prevent special characters like %28 from being decoded by the browser in the URL address bar? This problem has emerged in Angular v5.2.5.

Here is a demo showcasing this problem:

It should be noted that in Angular 6, this issue no longer exists:

Answer №1

The issue lies in not focusing on the correct parameters. In this example, it is evident that there is no need to encode the parameters.

Creating query parameters doesn't have to be complex with Angular's high level of abstraction. Take advantage of these features for smoother implementation.

ngOnInit(): void {
  this._route.queryParamMap
    .subscribe(params => {
      this.form.patchValue({
        query: params.get('query') || '',
      });
    });
}

public onSubmit(): void {
  const query: string = this.form.value.query;
  this._router.navigate(['/search'], {
    queryParams: {
      query
    }
  })
}

UPDATE utilizing matrix notation: view stackblitz

ngOnInit(): void {
  this._route.params
    .subscribe(params => {
      this.form.patchValue({
        query: params['query'] || '',
      });
    });
}

public onSubmit(): void {
  const query: string = this.form.value.query;
  this._router.navigate(['/search', { query }]);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display the thesaurus angular component

I received this JSON object: { "BTC_BCN": { "id": 7, "last": "0.00000021", "lowestAsk": "0.00000021", "highestBid": "0.00000020", "percentChange": "0.05000000", "baseVolume": "11.09583267", "quot ...

Wrapper functions that are nested are returning a Promise that resolves to another Promise of type T

I have a function called doesPromiseyThings that wraps a thunk and returns its value inside a Promise. I want to create another wrapper that not only handles the creation of thunks, but also ensures the returned type is a Promise-wrapped version of the ori ...

Explain a category of instance used in a template parameter

I am currently working on implementing a basic IOC container with type-checking capabilities. My goal is to pass the "register" method an abstract class type along with an instance of a derived type. In the "resolve" function, I aim to provide an abstrac ...

What is the method for obtaining the current participant's ID from the Angular frontend of a Hyperledger Composer application?

Need help with hyperledger-composer: I know how to retrieve the id of the current participant within a transaction processor function using this code: let currentParticipant = getCurrentParticipant(); let participantId = currentParticipant.getFullyQuali ...

Angular application seamlessly connects with Nodejs application

In my Node.js application, I utilized Express generated by express generator and implemented handlebars as the view engine. The application operates smoothly on port 3000. The defined routes in Express include: ... app.use('/', index); app.use( ...

Tips for avoiding the reconstruction of components in if-else conditions within Angular

After just joining the Angular4 club as a ReactJS developer, I find myself using basic conditional statements with a very simple condition. Take a look: <div class="app-component"> <app-country *ngIf="condition"></app-country> ...

The classification of a property is determined by the types of the other properties present

I am trying to figure out a way in Typescript to create a general component that takes a prop called component, with the remaining props being specific to that component. How can I achieve this? For example: <FormField component={Input} ... /> Thi ...

Guide for releasing a typescript package compatible with both node and react applications

I have developed an authentication library in TypeScript which I have released on npm. My goal is to make this library compatible for use in both Node.js projects and React projects created with create-react-app. However, I am facing an issue where one of ...

Encountering problems with displaying the index value in *ngFor directive in Angular 5

I am encountering a problem with rendering the index of *ngFor directive for a specific scenario as described below. Suppose we have an array of objects like this: this.temp = [ {name:'John',age:24,visibility:'visible'}, {name:&ap ...

What is the method to access a component from a module that has been imported into the app module?

We are currently working on a project that has the following hierarchy. app/ ├── app.component.html ├── app.component.ts ├── app.module.ts <--moduleA and moduleB is imported here ├── app-routing.module.ts ├── moduleA/ ...

Utilize ngrx and rxjs to transform an Observable from createSelector (TS2740: Type 'MemoizedSelector error)

My usual method of fetching data from the ngrx store used to be: public getUser(): Observable<IUser> { return this.store.select(store => store.users.selectedUser); } However, I am now attempting to transition to using createSelecor (ngrx 15) an ...

Angular form directive for managing arrays

export class TestComponent implements OnInit { models: Model[]; ngOnInit() { // numerous Observable pipes and subscriptions, one of which populates the models } add(): void { let newModel = {...}; this.models.push(ne ...

Is it possible to deduce a generic type from another generic type in TypeScript?

One of the functions I am working with is useFormState(), which requires an object initialValues of type FormType as a parameter. type FormType = { email: string; password: string; rememberMe: boolean; } ... const initialValues: FormType = { ...

Maintain the specific type based on the provided data, rather than the default value, when a related generic is defined

When it comes to unit tests, I prefer a more flexible approach with dynamic generic types that eliminate the need for type casting. I want T to be open-ended, but if I specify a type, I expect to receive an exact match. For R, I need it to precisely matc ...

Creating a custom sorting function in Typescript for arrays using a comparator

Looking to implement a custom sorting method for an array that consistently arrives in varying orders: [{code: 'A'},{code: 'O'},{code: 'I'}], [{code: 'O'},{code: 'A'},{code: 'I'}], ... The desir ...

Issue with Angular Reactive Form Validation Functionality Failure

Recently, I've been experimenting with Angular Reactive forms and encountered an issue in my code. Here's the link to the Component Class file I created for the component class. Additionally, you can view my HTML code by following this link: HTM ...

What is the proper way to integrate plotly types in Angular using a local version?

After exploring various plotly packages, I discovered that the angular-plotly package is no longer being updated. To incorporate the plotly library into my project, I decided to download the plotly.min.js file and include it in my sources. Additionally, I ...

Angular: Reacting to events with SVG attributes

Is there a way to access the attribute (e.g. fill) of an SVG object using an Angular event (e.g. mouseenter)? I attempted these different variations but had no success. <rect #rrr [attr.fill]="'green'" (mouseenter)="rrr.fill=&a ...

run a function once ngFor has completed rendering the data

I'm attempting to run a function every time my ngFor finishes loading data from the API. However, the callback only works on the initial load of the ngFor. How can I make sure that the callback is executed whenever my ngFor data changes? I found a ...

Is it possible to efficiently structure intricate JSON data onto interfaces in TypeScript with the incorporation of observables?

I am currently working on creating a simple web news reader that relies heavily on the Google News API (). I have set up all the necessary services, models, etc. However, I am having difficulty mapping the data onto specific interfaces. The Google API retu ...