Search code examples
angularangular6angular-httpclient

Angular HttpClient get request URL removes hashtag/number sign


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?

Solution

  • 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);
      }
    }