3

I'm using httpclient get, when I have a # in the request URL it removes everything after the #

Example:

Intended Request:

https://jsonplaceholder.typicode.com/users/1#TEST

Actual Request:

https://jsonplaceholder.typicode.com/users/1

I tried using PathLocationStrategy, but its only effecting router links.

Made a slackblitz example, it has the PathLocationStrategy also.

Stackblitz: https://stackblitz.com/edit/angular-http-client-p5yrdq

enter image description here

  1. Why does this happen?
  2. Any solutions/workaround?
Dan Def
  • 1,836
  • 2
  • 21
  • 39
Shank
  • 1,387
  • 11
  • 32

1 Answers1

4

My solution was to intercept and encode the url and parameters.

app.module.ts

providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: EncodeHttpParamsInterceptor,
      multi: true,
    },

EncodeHttpParamsInterceptor

@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()});
    const httpUrlEncoding = new HttpUrlEncodingCodec();
    return next.handle(req.clone({
      params,
      url: httpUrlEncoding.encodeValue(req.url),
    }));
  }
}

CustomEncoder

export 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);
  }
}
Shank
  • 1,387
  • 11
  • 32