Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 2 disable url encoding

I would like to disable url encoding.

When I use this below.

this.router.navigate(['/profile', { tags: 'one,two' }]);

The url is like this

http://localhost:4200/profile;tags=one%2Ctwo

I would like it to be pretty like below

http://localhost:4200/profile;tags=one,two

Is there a way to disable the url encoding?

like image 569
Jason Avatar asked Jan 05 '17 01:01

Jason


People also ask

How to avoid encoding in url angular?

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

How do I encode URL in Golang?

URL Encoding or Escaping a String in Go Go provides the following two functions to encode or escape a string so that it can be safely placed inside a URL: QueryEscape(): Encode a string to be safely placed inside a URL query string. PathEscape(): Encode a string to be safely placed inside a URL path segment.


1 Answers

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.

like image 128
jigar gala Avatar answered Oct 03 '22 01:10

jigar gala