Check the docs for RouterLink:

  • [routerLink] is used to pass what comes before the ?, called "params".
  • [queryParams] is used to pass what comes after the ?, called "query params".

So, to solve your issue, a possible solution is to return an object from getPageUrl instead of a string, the object will have both the params and query params:

public getPageUrl(pageNumber: number): Observable<string> {
    return this.route.url.pipe(
      map((segments: UrlSegment[]) => {
        return {params: segments, queryParams: {startIndex: pageNumber};
      })
    );
  }

and you use it like this:

<a *ngIf="getPageUrl(item) | async as url"
   class="page-link"
   [routerLink]="url.params"
   [queryParams]="url.queryParams">{{ item }}</a

Notice you don't need to join the query segments with /, because routerLink accepts an array too.

Answer from DWilches on Stack Overflow
🌐
GitHub
github.com › angular › angular › issues › 28917
router.navigate option to disable URI encoding / ability to control serialization without writing a whole UrlSerializer implementation · Issue #28917 · angular/angular
February 22, 2019 - Then the user can avoid this problem by encoding each parameter just once. This parameter could be an option in router.navigate, (easy for a user to notice) Alternatively a module option in RouterModule.forRoot(routes, { enableTracing: true, initialNavigation: true, relativeLinkResolution: 'corrected', // Fix Router BUG disableUrlEncoding: true // Suggest something like this: but would need documentation } navigateByUrl: but I would prefer not to construct absolute URL's ( with possibly unexpected limitations)
Author   angular
Top answer
1 of 4
9

Update: with the new httpParamSerializer in Angular 1.4 you can do it by writing your own paramSerializer and setting $httpProvider.defaults.paramSerializer.

Below only applies to AngularJS 1.3 (and older).

It is not possible without changing the source of AngularJS.

This is done by $http:

https://github.com/angular/angular.js/tree/v1.3.0-rc.5/src/ng/http.js#L1057

function buildUrl(url, params) {
      if (!params) return url;
      var parts = [];
      forEachSorted(params, function(value, key) {
        if (value === null || isUndefined(value)) return;
        if (!isArray(value)) value = [value];

        forEach(value, function(v) {
          if (isObject(v)) {
            v = toJson(v);
          }
          parts.push(encodeUriQuery(key) + '=' +
                     encodeUriQuery(v));
        });
      });
      if(parts.length > 0) {
        url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
      }
      return url;
}

encodeUriQuery uses the standard encodeUriComponent (MDN) which replaces the '+' with '%2B'

Too bad you cannot overwrite encodeUriQuery because it is a local variable inside the angular function.

So the only option I see is to overwrite window.encodeURIComponent. I've done it in an $http interceptor to minimize the impact. Note that the original function is only put back when the response comes back, so this change is global (!!) while your request is ongoing. So be sure to test if this doesn't break something else in your application.

app.config(function($httpProvider) {
  $httpProvider.interceptors.push(function($q) {
    var realEncodeURIComponent = window.encodeURIComponent;
    return {
      'request': function(config) {
         window.encodeURIComponent = function(input) {
           return realEncodeURIComponent(input).split("%2B").join("+"); 
         }; 
         return config || $q.when(config);
      },
      'response': function(config) {
         window.encodeURIComponent = realEncodeURIComponent;
         return config || $q.when(config);
      }
    };
  });
});
2 of 4
4

AngularJS only runs the encodeUriQuery method if you pass your params as an extra object. If you manually create your own param string and concatenate it onto your URL then Angular won't modify it.

It's pretty simple to convert the param object yourself, here's an example: How to serialize an Object into a list of parameters?

🌐
Mauriciomontejo
mauriciomontejo.com › vlqws › r2y7lgf.php
Disable url encoding in angular 8
The encodeURIComponent() function ... the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters). Given an encoded URL and the task is to decode the encoded URL using AngularJS. angular bootstrap not working update angular cli Normally, Angular automatically sanitizes the URL, disables the dangerous ...
🌐
Radzen
forum.radzen.com › radzen studio › angular
How to prevent encoding of url parameters - Angular - Radzen
August 11, 2020 - @staff Hi. How can i prevent URL parameters from being encoded? Use-case: Page 1: Based on REST data source_1; Datagrid with button column that passes the object id for that row to a new Dialog Page. Page 2 (being…
🌐
GitHub
github.com › angular › angular › issues › 38706
Avoid default encoding of queryParams in Angular · Issue #38706 · angular/angular
September 4, 2020 - import {UrlSerializer, UrlTree, DefaultUrlSerializer} from '@angular/router'; export class CustomUrlSerializer implements UrlSerializer { public ds = new DefaultUrlSerializer(); parse(url: any): UrlTree { return this.ds.parse(url); } serialize(tree: UrlTree): any { const serializedUrl = this.ds.serialize(tree); return serializedUrl .replace(/@/gi, '@') .replace(/:/gi, ':') .replace(/$/gi, '$') .replace(/,/gi, ',') .replace(/;/gi, ';') .replace(/ /gi, '+') .replace(/=/gi, '=') .replace(/?/gi, '?') .replace(///gi, '/'); } }
Author   angular
🌐
Stack Overflow
stackoverflow.com › questions › 58813660 › remove-html-encode-character-from-link-in-angular8
angular - Remove Html Encode Character From Link In Angular8 - Stack Overflow
November 12, 2019 - The string that you show on screen is indeed encoded with encodeURIComponent so if you use the opposite decodeURIComponent on that string you will get the url.
Find elsewhere
🌐
Angular
v17.angular.io › api › common › http › HttpUrlEncodingCodec
Angular
Angular is a platform for building mobile and desktop web applications. Join the community of millions of developers who build compelling user interfaces with Angular.
🌐
Stack Overflow
stackoverflow.com › questions › 39756564 › stop-resource-from-encoding-url
angularjs - stop $resource from encoding URL - Stack Overflow
Is there a way to keep my url from being URL encoded · http://localhost:5000/trip/v1/driving/polyline(_p~iF~ps|U_ulLnnqCwugHqniHzxtZorpA~l~D}clLdvxAcqjOeftBgawM}ujM}krKs{rFbidPsrtD}x~TzzqNa|wF??l_uW}flAqcjEmnuPo`lGungJcriNa|wF{HadC}HuaBqEewBt\k}AyRslCcVslCfLabDpEwaB).json?steps=true&overview=simplified ... I'm not sure I follow.... ... NM. I got it. Just used my :waypoints ref in the $resource to keep it from getting encoded. Thx for the suggestion. ... How the creator of Angular is dehydrating the web (Ep.
🌐
Stack Overflow
stackoverflow.com › questions › 55417376 › how-to-avoid-decoding-url-with-params-on-reload
angular - How to avoid decoding url with params on reload - Stack Overflow
March 29, 2019 - If a Link in an email contains an absolute URL-Path with Query-Param, Angular decodes this. Navigation from menu works on this way <a [routerLink]="node.application.path" [queryParams]="{ reiter: node.application.argument}" (click)="onClickLink(node)">{{ node.name }}</a> Result is a link like this example: http://localhost:4200/#/service/wissen/content/74433?reiter=74427 · On reloading the Page, this will encoded to: http://localhost:4200/#/service/wissen/content/74433?reiter=74427
🌐
GitHub
github.com › angular-ui › ui-router › issues › 3374
how to avoid URL encoding · Issue #3374 · angular-ui/ui-router
March 16, 2017 - You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session. ... sourceUrl:"http://www.techradar.com/news/mobile-computing/laptops/xiaomi-s-first-laptop-is-an-affordable-macbook-air-clone-for-windows-fans-1325480" I have a search parameter with this value and each time you press enter a $ state.go is launched and I have a url encoder which failed my query
Author   angular-ui
Top answer
1 of 2
3

Angular2 by default uses encodeURIComponent() to encode queryParams in URL, you can avoid it by writing custom URL serializer and override default functionality.

In my case, I wanted to avoid Angular2 to avoid replacing comma(,) by (%2). I was passing Query as lang=en-us,en-uk where it was getting converted to lang=en-us%2en-uk.

Here how I worked it out:

CustomUrlSerializer.ts

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

export class CustomUrlSerializer implements UrlSerializer {
    parse(url: any): UrlTree {
        let dus = new DefaultUrlSerializer();
        return dus.parse(url);
    }

    serialize(tree: UrlTree): any {
        let dus = new DefaultUrlSerializer(),
            path = dus.serialize(tree);
        // use your regex to replace as per your requirement.
        return path.replace(/%2/g,',');
    }
}

Add below line to your main appModule.ts

import {UrlSerializer} from '@angular/router';
import {CustomUrlSerializer} from './CustomUrlSerializer';

@NgModule({
    providers: [{ provide: UrlSerializer, useClass: CustomUrlSerializer }]
})

This won't break your default functionality and take cares of URL as per your need.

2 of 2
1

You can't prevent slashes from being encoded. I'd use matrix parameters which look cleaner.

http://page.com/home/example;a=foo;b=bar;c=baz/something

You can use Router's navigate method to use them

this.router.navigate(['/home', '/example', { a: 'foo', b: 'bar', c: 'baz' }, '/something']);

To get current params, use ActivatedRoute's params property to which you can subscribe.

🌐
Stack Overflow
stackoverflow.com › questions › 42114035 › how-to-avoid-the-encoding-of-parameter-added-to-url-in-angular-js
How to avoid the encoding of parameter added to URL in Angular Js
In my angular JS application I'm dynamically adding a parameter to the URL of the page. Say my page URL is www.hello.com/products , using $location.path I'm just appending a value to URL, and now m...
🌐
Better Programming
betterprogramming.pub › how-to-fix-angular-httpclient-not-escaping-url-parameters-ddce3f9b8746
How To Fix Angular HttpClient Not Escaping URL Parameters | by Ali Kamalizade | Better Programming
March 28, 2023 - How To Fix Angular HttpClient Not Escaping URL Parameters Creating a custom HttpParameterCodec to encode everything The Angular Http Client was introduced in Angular 4.3 and works better than the old …