Angular url plus sign converting to space

后端 未结 7 1589
梦如初夏
梦如初夏 2020-11-29 06:02

I have angular application where i want to pass plus sign + in query string like:

http://localhost:3000/page?name=xyz+manwal
7条回答
  •  孤街浪徒
    2020-11-29 06:59

    In Angular 5.2.7+ the "+" is replaced with space " " in a query string.

    Here is the corresponding commit : fix(router): fix URL serialization

    If you want to change this behaviour and replace the "+" with "%2B" you can create a custom url serializer and provide it in the AppModule providers.

    import { DefaultUrlSerializer, UrlSerializer, UrlTree } from '@angular/router';
    
    export default class CustomUrlSerializer implements UrlSerializer {
        private _defaultUrlSerializer: DefaultUrlSerializer = new DefaultUrlSerializer();
    
        parse(url: string): UrlTree {
            // Encode "+" to "%2B"
            url = url.replace(/\+/gi, '%2B');
            // Use the default serializer.
            return this._defaultUrlSerializer.parse(url);
        }
    
        serialize(tree: UrlTree): string {
            return this._defaultUrlSerializer.serialize(tree).replace(/\+/gi, '%2B');
        }
    }
    
    @NgModule({
        imports: [
            BrowserModule,
            BrowserAnimationsModule,
            AppRoutingModule
        ],
        declarations: [
            AppComponent
        ],
        providers: [
            { provide: UrlSerializer, useClass: CustomUrlSerializer }
        ],
    
        entryComponents: [],
        bootstrap: [AppComponent]
    })
    export class AppModule {
    }
    

    http://localhost:3000/page?name=xyz+manwal

    The URL will be converted to:

    http://localhost:3000/page?name=xyz%2Bmanwal

    Hope this will help.

提交回复
热议问题