【问题标题】:Angular HttpClient get request URL removes hashtag/number signAngular HttpClient 获取请求 URL 删除主题标签/数字符号
【发布时间】:2019-06-26 08:31:17
【问题描述】:

我正在使用 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. 任何解决方案/解决方法?

【问题讨论】:

标签: angular angular6 angular-httpclient


【解决方案1】:

我的解决方案是截取并编码 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);
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-13
    • 1970-01-01
    • 2011-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多