Angular url plus sign converting to space

后端 未结 7 1571
梦如初夏
梦如初夏 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 07:09

    You can override default angular encoding with adding Interceptor which fixes this:

    import { HttpInterceptor, HttpRequest, HttpEvent, HttpHandler, HttpParams, HttpParameterCodec } from "@angular/common/http";
    import { Injectable } from "@angular/core";
    import { Observable } from "rxjs";
    
    @Injectable()
    export class EncodeHttpParamsInterceptor implements HttpInterceptor {
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const params = new HttpParams({encoder: new CustomEncoder(), fromString: req.params.toString()});
        return next.handle(req.clone({params}));
      }
    }
    
    
    class CustomEncoder implements HttpParameterCodec {
      encodeKey(key: string): string {
        return encodeURIComponent(key);
      }
    
      encodeValue(value: string): string {
        return encodeURIComponent(value);
      }
    
      decodeKey(key: string): string {
        return decodeURIComponent(key);
      }
    
      decodeValue(value: string): string {
        return decodeURIComponent(value);
      }
    }
    

    and declare it in providers section of in app.module.ts

    providers: [
        {
          provide: HTTP_INTERCEPTORS,
          useClass: EncodeHttpParamsInterceptor,
          multi: true
        }
    ]
    
    0 讨论(0)
提交回复
热议问题