Angular HttpClient 获取请求 URL 删除主题标签/数字符号 [英] Angular HttpClient get request URL removes hashtag/number sign

查看:21
本文介绍了Angular HttpClient 获取请求 URL 删除主题标签/数字符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

之后的所有内容

示例:

预期请求:

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

实际请求:

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

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

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

Stackblitz:

  1. 为什么会发生这种情况?
  2. 任何解决方案/解决方法?

解决方案

我的解决方案是对 url 和参数进行拦截和编码.

app.module.ts

提供者:[{提供:HTTP_INTERCEPTORS,useClass: EncodeHttpParamsInterceptor,多:真实,},

EncodeHttpParamsInterceptor

@Injectable()导出类 EncodeHttpParamsInterceptor 实现 HttpInterceptor {拦截(req: HttpRequest, next: HttpHandler): Observable>{const params = new HttpParams({encoder: new CustomEncoder(), fromString: req.params.toString()});const httpUrlEncoding = new HttpUrlEncodingCodec();返回 next.handle(req.clone({参数,网址:httpUrlEncoding.encodeValue(req.url),}));}}

自定义编码器

导出类 CustomEncoder 实现 HttpParameterCodec {编码键(键:字符串):字符串{返回 encodeURIComponent(key);}编码值(值:字符串):字符串{返回 encodeURIComponent(value);}decodeKey(key: string): string {返回 decodeURIComponent(key);}decodeValue(值:字符串):字符串{返回 decodeURIComponent(value);}}

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

  1. Why does this happen?
  2. Any solutions/workaround?

解决方案

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

这篇关于Angular HttpClient 获取请求 URL 删除主题标签/数字符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆