Angular HttpClient 获取请求 URL 删除 hashtag/number 标志

Angular HttpClient get request URL removes hashtag/number sign

我正在使用 httpclient get,当我在请求 URL 中有 # 时,它会删除 #

之后的所有内容

示例:

预期请求:

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

实际请求:

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

我尝试使用 PathLocationStrategy,但它只影响路由器链接。

做了一个slackblitz的例子,它也有PathLocationStrategy。

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

  1. 为什么会这样?
  2. 任何 solutions/workaround?

我的解决方案是拦截并编码 url 和参数。

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

自定义编码器

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