angular 2 disable url encoding

梦想的初衷 提交于 2019-11-26 17:52:54

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.

The url looks like this:

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

But it won't bring any problem when you consume it. If you, for the 'profile' route, set up a 'canActive' guard with code like following:

  canActivate(route: ActivatedRouteSnapshot) {
    console.log(route.params);}

And when you navigating to http://localhost:4200/profile;tags=one%2Ctwo, you will see {tag: one, two} in the console. So when you consume it, it is 'one, two'. And of course, you can copy this encoded url and send to others to use.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!